2

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?

Community
  • 1
  • 1
Foxy
  • 416
  • 8
  • 18
  • does the nested class have to be a specific `HashMap` or `TreeMap`, or can it be the common interface `Map`? – nandsito Mar 16 '17 at 18:05
  • Did you try treeMap.putAll(hashMap); ? https://repl.it/GZO1/0 – 0190198 Mar 16 '17 at 18:06
  • @nandsito backend has it as HashMap and passes to front as an attribute, if I change backend it is better change it to TreeMap then, I just didn't want to touch backend as it was already developed by another developer, was trying to find solution in jsp page. – Foxy Mar 16 '17 at 18:08
  • @K.S I did, it works if you have primitive value or String as parameters but as I said if I have nested map with my bean class it gives me error. – Foxy Mar 16 '17 at 18:10

2 Answers2

1

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()));
Klitos Kyriacou
  • 10,634
  • 2
  • 38
  • 70
0

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.

nandsito
  • 3,782
  • 2
  • 19
  • 26