Foxy
Foxy

Reputation: 416

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:

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<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. 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?

Upvotes: 2

Views: 3519

Answers (2)

Klitos Kyriacou
Klitos Kyriacou

Reputation: 11621

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

Upvotes: 1

nandsito
nandsito

Reputation: 3852

If your code uses the nested map as a regular Map, i.e. it doesn't use any specific method defined in HashMap or TreeMap, you can define the type parameter of your variables using Map instead:

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.

Upvotes: 0

Related Questions