2017-02-12 116 views
3

我試圖做到這一點下面的代碼:與集合轉換集合

Map<Node, TreeSet<String>> childrenNodes = new TreeMap<>(getAll()); 

我把下面getAllNodesAndEdges方法的標題:

public Map<Node, Set<String>> getAll() {...} 

我需要轉換一個普通地圖和設定在它的內部分爲TreeMapTreeSet以進行分類打印。但是,第一段代碼有編譯錯誤,說"Cannot infer type arguments for TreeMap<>"

什麼是解決這個問題的最好方法?

編輯:下面

更多信息在Information.java

public Map<Node, Set<String>> getAll() { 
     return this.all; 
} 

然而,test1.java需要使用代碼

Map<Node, HashSet<String>> all = getAll() 

test2.java需要使用的代碼

Map<Node, TreeSet<String>> childrenNodes = new TreeMap<Node, TreeSet<String>>(getAll()); 

但兩者運行類型不匹配的編譯錯誤

第一:

Type mismatch: cannot convert from Map<Node,Set<String>> to Map<Node,HashSet<String>> 

第二:

The construtor TreeMap<Node,TreeSet<String>>(Map<Node,Set<String>>) is undefined 
+0

您需要的類型參數在'<>'內。它們不能被自動推斷,正如錯誤說 –

+0

或者你可以讓'getAll'自行返回一個TreeMap –

+0

@ cricket_007我會怎麼做呢? – Michael

回答

2

您必須爲新地圖的值創建新對象。

Map<Node, TreeSet<String>> converted = new TreeMap<>(); 

for(Entry<Node, Set<String>> entry : childrenNodes.entrySet()){ 
    converted.put(entry.getKey(), new TreeSet<>(entry.getValue())); 
} 
+0

決定,因爲這是最適合我的方案中使用此解決方案,旨在感謝 – Michael

0

不能在這樣的方式做到這一點。

您可以執行:

1)的變化類型變量childrenNodes的:

Map<Node, Set<String>> childrenNodes = new TreeMap<>(getAll()); 

即不Map<Node, TreeSet<String>>,但Map<Node, Set<String>>

要麼

2)使getAll()返回類型

Map<Node, TreeSet<String>> getAll() 

編譯器的錯誤告訴你到底這個東西:它是不可能的推斷TreeSet<String>Set<String>。它是大致說與嘗試這種類型的任務相同:HashMap<String> foo = getMap();其中getMap()簡單地返回Map<String>

+0

我的困境是,我需要childrenNodes成爲Map >,因爲它需要對已排序的字符串。但是,有時需要將返回值設置爲Map >。所以如果沒有辦法做到這一點,是不是最好創建另一個方法,一個返回TreeSet,一個返回Hash ? – Michael

+0

對,你不能做這樣的事情。它就像在說:我想通過'Map '來變量,但有時候會有整數值。其實,你*可以做到這一點,但忘記了類型變量,使用原始類型。或者,使用大多數的基礎類型(在你的情況下它是'Set ')。 – Andremoniy

+0

@PatrickParker遺憾,對他們來說,這是郵件處理?對我來說,還是邁克爾? – Andremoniy

0

您不能僅將一種類型的Set(TreeSet,HashSet)強制轉換爲另一種類型。您需要通過供應商,例如TreeSet::new,通過方法參數。

private final Map<Node, Set<String>> all; 

public <S extends Set<String>, M extends Map<Node, S>> M getAll(Supplier<M> mapFactory, Supplier<S> setFactory) { 
    return all.entrySet().stream() 
     .collect(Collectors.toMap(
      Map.Entry::getKey, 
      e -> e.getValue().stream().collect(Collectors.toCollection(setFactory)), 
      (v1, v2) -> v1, 
      mapFactory)); 
} 

那麼你會這樣稱呼它:

Map<Node, HashSet<String>> test1 = getAll(HashMap::new, HashSet::new); 
Map<Node, TreeSet<String>> test2 = getAll(TreeMap::new, TreeSet::new); 

或者更好的是,使用排序接口而不是實現類的局部變量類型:

Map<Node, Set<String>> test1 = getAll(HashMap::new, HashSet::new); 
SortedMap<Node, SortedSet<String>> test2 = getAll(TreeMap::new, TreeSet::new);