In the last tutorial I have shared Treemap iterator example. TreeMap is always sorted based on its keys, in this post we will see how to sort it based on the values. We will sort TreeMap based on values using Comparator.Below is the code for sorting TreeMap by values.
Program for sorting TreeMap by Values in Java
import java.util.*;
public class TreeMapSortByValue {
public static void main(String args[]) {
// Declaring a TreeMap of String keys and String values
TreeMapString, String> treemap = new TreeMapString, String>();
// Add Key-Value pairs to TreeMap
treemap.put("Key1", "Pear");
treemap.put("Key2", "Apple");
treemap.put("Key3", "Orange");
treemap.put("Key4", "Papaya");
treemap.put("Key5", "Banana");
//sort treemap by values
Map sortedMap = sortByValues(treemap);
// Get Set of entries
Set set = sortedMap.entrySet();
// Get iterator
Iterator it = set.iterator();
// Show TreeMap elements
System.out.println("TreeMap contains: ");
while(it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.print("Key is: "+pair.getKey() + " and ");
System.out.println("Value is: "+pair.getValue());
}
}
public static K, V extends ComparableV>> MapK, V>
sortByValues(final MapK, V> map) {
ComparatorK> valueComparator =
new ComparatorK>() {
public int compare(K k1, K k2) {
int compare =
map.get(k1).compareTo(map.get(k2));
if (compare == 0)
return 1;
else
return compare;
}
};
MapK, V> sortedByValues =
new TreeMapK, V>(valueComparator);
sortedByValues.putAll(map);
return sortedByValues;
}
}
Output
TreeMap contains:
Key is: Key2 and Value is: Apple
Key is: Key5 and Value is: Banana
Key is: Key3 and Value is: Orange
Key is: Key4 and Value is: Papaya
Key is: Key1 and Value is: Pear