Java Map sort keys by numerical value descending order

Description

Java Map sort keys by numerical value descending order

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

public class Main {
  public static void main(String[] args) {
    Map<Integer, String> map = new TreeMap<Integer, String>(new MyComparator());

    map.put(2, "HTML");
    map.put(3, "Java");
    map.put(4, "SQL");
    map.put(1, "CSS");

    System.out.println(map);/*from w  w w. j  av  a2  s  .c om*/
  }

}

class MyComparator implements Comparator<Integer> {

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

    return second.compareTo(first);
  }
}



PreviousNext

Related