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.
new TreeMap<Integer, String[]>(hashMap).descendingMap()