2017-03-16 181 views
0

這個問題似乎非常流行,但我無法得到正確的結果爲我的實現。我以這個thread爲例,但到目前爲止沒有運氣。如何將HashMap轉換爲TreeMap

這裏我有HashMap的,我需要轉換爲TreeMap中才能有鍵值進行排序:

HasMap<String, HashMap<String, SomeBean>> hashMap = (HashMap<String, HashMap<String, SomeBean>>)request.getAttribute("HASHMAP"); 

應用迭代後,我可以看到在未分類順序結果。

現在我想將其轉換爲TreeMap的:

TreeMap<String, TreeMap<String, SomeBean>> treeMap = new TreeMap<String, TreeMap<String, SomeBean>>(hashMap); 

結果:

The constructor TreeMap<String,TreeMap<String,SomeBean>>(HashMap<String,HashMap<String,SomeBean>>) is undefined 

嗯,好像是因爲我有嵌套的地圖我的bean類是不是讓我來創建新樹地圖。這是可以理解的,因爲我不希望TreeMap具有適合我的標準的構造函數,但問題是如何找到解決此問題的解決方法?

+0

確實嵌套類必須特定'HashMap'或'TreeMap',也可以是普通界面'地圖'? – nandsito

+0

您是否嘗試過使用treeMap.putAll(hashMap); ? https://repl.it/GZO1/0 –

+0

@nandsito後端將它作爲HashMap並作爲屬性傳遞給前端,如果我更改後端,最好將其更改爲TreeMap,然後我不想將後端作爲後端它已經由另一個開發人員開發,試圖在jsp頁面中找到解決方案。 – Foxy

回答

0

如果你的代碼使用嵌套的地圖作爲一個普通Map,即不使用HashMapTreeMap定義的任何具體方法,你可以使用Map而不是定義變量的類型參數:

HashMap<String, Map<String, SomeBean>> hashMap = 
    (HashMap<String, Map<String, SomeBean>>) request.getAttribute("HASHMAP"); 

TreeMap<String, Map<String, SomeBean>> treeMap = 
    new TreeMap<String, Map<String, SomeBean>>(hashMap); 

否則,您將無法使用constructor(Map)putAll(Map),您將不得不手動填寫treeMap

0

由於您的地圖有不兼容的值類型,你需要將它們手動轉換:

Map<String, Map<String, SomeBean>> treeMap = new TreeMap<>(); 
    for (Map.Entry<String, HashMap<String, Integer>> e : hashMap.entrySet()) 
     treeMap.put(e.getKey(), new TreeMap<>(e.getValue()));