This Post about sorting TreeMap.
TreeMap Actually sorts values by key. Inorder to sort Map by values we have to use comparator. The below program illustrates this.
public class ComparatorClassDemo {
public static void main(String[] args) {
HashMap<Integer,String> map = new HashMap<Integer,String>();
ValueComparator bvc = new ValueComparator(map);
TreeMap<Integer,String> sorted_map = new TreeMap(bvc);
map.put(1,"Arogya");
map.put(2,"wer");
map.put(3,"dfg");
map.put(6,"io");
map.put(5,"lkaldfk");
map.put(4,"bkjaskj");
System.out.println("Before usage of comparator"+map);
sorted_map.putAll(map);
System.out.println("results");
for (int key : sorted_map.keySet()) {
System.out.println("key/value: " + key + "/"+sorted_map.get(key));
}
}
}
class ValueComparator implements Comparator {
Map base;
public ValueComparator(Map base) {
this.base = base;
}
public int compare(Object a, Object b) {
String name=(String)base.get(a);
String name1=(String)base.get(b);
return name.compareTo(name1);
}
}
OutPut:
{2=wer, 4=bkjaskj, 6=io, 1=Arogya, 3=dfg, 5=lkaldfk}
results
key/value: 1/Arogya
key/value: 4/bkjaskj
key/value: 3/dfg
key/value: 6/io
key/value: 5/lkaldfk
key/value: 2/wer