How to use SortedMap interface or TreeMap in Java?

I would use TreeMap, which implements SortedMap. It is designed exactly for that. Example: Map<Integer, String> map = new TreeMap<Integer, String>(); // Add Items to the TreeMap map.put(1, “One”); map.put(2, “Two”); map.put(3, “Three”); // Iterate over them for (Map.Entry<Integer, String> entry : map.entrySet()) { System.out.println(entry.getKey() + ” => ” + entry.getValue()); } See the Java … Read more

Java TreeMap Comparator

You can not sort TreeMap on values. A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used You will need to provide comparator for Comparator<? super K> so your comparator should compare … Read more