Java program to sort a map by value.

Question:
How to sort or order a HashMap or TreeSet or any map item by value?

Answer:
Write a comparator which compares by value, not by key.

Code:
import java.util.*;
import java.util.Map.*;
 
public class SortHashMap {
 
  public static void main(String a[]){
 
    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("apple", 20);
    map.put("plum", 11);
    map.put("orange", 16);
    map.put("peach", 3);
    map.put("grape", 7);
 
    Set<Entry<String,Integer>> set = map.entrySet();
    List<Entry<String,Integer>> list = new ArrayList<Entry<String,Integer>>(set);
 
    Collections.sort(list, new Comparator<Map.Entry<String,Integer>>() {
      public int compare( Map.Entry<String,Integer> o1, Map.Entry<String,Integer> o2) {
        return (o2.getValue()).compareTo( o1.getValue());
      }
    });
 
    for(Map.Entry<String, Integer> entry:list){
      System.out.println(entry.getValue() + " " + entry.getKey());
    }
  }
}

Output:
$ java SortHashMap
20 apple
16 orange
11 plum
7 grape
3 peach