Java Collection How to - Sort Hashmap keys by numerical value descending order








Question

We would like to know how to sort Hashmap keys by numerical value descending order.

Answer

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
//from w  w w  . j  av  a 2s .co  m
public class Main {
  public static void main(String[] args) {
    Map<Integer, String> map = new TreeMap<Integer, String>(new MyComparator());

    map.put(2, "v");
    map.put(3, "h");
    map.put(4, "e");
    map.put(1, "a");

    System.out.println(map);
  }

}

class MyComparator implements Comparator<Integer> {

  @Override
  public int compare(Integer first, Integer second) {

    return second.compareTo(first);
  }
}

The code above generates the following result.