2017-03-16 102 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()));