Java Language Comparable and Comparator Sorting Map entries


As of Java 8, there are default methods on the Map.Entry interface to allow sorting of map iterations.

Java SE 8
Map<String, Integer> numberOfEmployees = new HashMap<>();
numberOfEmployees.put("executives", 10);
numberOfEmployees.put("human ressources", 32);
numberOfEmployees.put("accounting", 12);
numberOfEmployees.put("IT", 100);

// Output the smallest departement in terms of number of employees
    .forEach(System.out::println);   // outputs : executives=10

Of course, these can also be used outside of the stream api :

Java SE 8
List<Map.Entry<String, Integer>> entries = new ArrayList<>(numberOfEmployees.entrySet());
Collections.sort(entries, Map.Entry.comparingByValue());