msagala - 1 year ago 82
Java Question

Using HashMap and Sort it using TreeMap with Descending Key Values

I have this code to populate a

`HashMap`
and pass it to
`TreeMap`
to sort it in natural order in
`Key`
values.

``````    Map<Integer, String[]> hashMap = new HashMap<Integer, String[]>();
hashMap.put(3, new String[]{"1","2"});
hashMap.put(2, new String[]{"1","2"});
hashMap.put(4, new String[]{"1","2"});
hashMap.put(1, new String[]{"1","2"});

System.out.println(hashMap);

Map<Integer, String[]> treeMap = new TreeMap<Integer, String[]>(hashMap);

System.out.println(hashMap); // Natural Order, Ascending
``````

Now my problems is, How can I sort my
`treeMap`
in
`Descending`
order? I've prepared my Comparator class named
`KeyComparator`
that sort
`Key`
to descending order. Here is my code below:

``````public class KeyComparator implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
if (o1 < o2) {
return 1;
} else if (o1 > o2) {
return -1;
} else {
return 0;
}
}
}
``````

The
`TreeMap`
has no 2 parameterized Constructor like for example
`TreeMap(new KeyComparator(),hashMap)`
. How can I use my
`KeyComparator`
class at the same time use to load the
`hashMap`
into my
`treeMap`
.

Do it like below, Create a treemap with `Comparator` and then use `putAll` method to pass the hashmap to it.

``````Map<Integer, String[]> treeMap = new TreeMap<Integer, String[]>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if (o1 < o2) {
return 1;
} else if (o1 > o2) {
return -1;
} else {
return 0;
}
}
});
treeMap.putAll(hashMap);

System.out.println(treeMap); // Descending
``````

Note:- In the example above, I have passed an anonymous implementation of `Comparator`. You can always pass the `KeyComparator` in the constructor.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download