简体   繁体   English

如何将HashMap转换为TreeMap

[英]How to convert HashMap to TreeMap

This question seems to be very popular and yet I couldn't get correct results for my implementation. 这个问题似乎很受欢迎,但是我无法获得正确的实施结果。 I had this thread as an example but so far no luck. 我以这个线程为例,但到目前为止还没有运气。

Here I have HashMap that I need to convert to TreeMap in order to have key values sorted: 在这里,我需要将HashMap转换为TreeMap以便对键值进行排序:

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

After applying iterator I could see results in unsorted order. 应用迭代器后,我可以看到未排序顺序的结果。

Now I want to convert it to TreeMap: 现在,我想将其转换为TreeMap:

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

Result: 结果:

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

Well, it seems because i have nested map with my bean class it is not allowing me to create new tree map. 好吧,似乎是因为我在我的bean类中嵌套了地图,所以不允许我创建新的树形地图。 It is understandable as I don't expect TreeMap to have constructor that suits my criteria but the question is how do I find workaround for this problem? 这是可以理解的,因为我不希望TreeMap具有适合我的条件的构造函数,但问题是如何找到解决此问题的方法?

If your code uses the nested map as a regular Map , ie it doesn't use any specific method defined in HashMap or TreeMap , you can define the type parameter of your variables using Map instead: 如果您的代码将嵌套映射用作常规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);

Or else, you won't be able to use constructor(Map) or putAll(Map) , and you will have to fill in the treeMap manually. 否则,您将无法使用constructor(Map)putAll(Map) ,并且必须手动填写treeMap

Since your maps have incompatible value types, you'll need to convert them manually: 由于您的地图具有不兼容的值类型,因此您需要手动对其进行转换:

    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()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM