How to sort A Map by Value in Java 8+

This has been one of the most frequently asked questions in Java interviews. With streams introduced after Java 8, this can be achieved in an elegant and functional way.

For example, let us consider I have a map having a word and its corresponding counts in a particular document as below:

final Map<String, Integer> wordCounts = new HashMap<>();
wordCounts.put("USA", 100);
wordCounts.put("jobs", 200);
wordCounts.put("software", 50);
wordCounts.put("technology", 70);
wordCounts.put("opportunity", 200);

Now, if I have to sort this map with value in ascending order, then it would be simplest and readable as below:

final Map<String, Integer> sortedByCount = wordCounts.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

Here, I am using LinkedHashMap to store the sorted result to preserve the order of the elements in the resulting map.

The advantages of this approach are:

  1. It doesn't modify the original data wordCounts making it more thread safe.
  2. It is more readable.

If you want to sort a map in reverse order, then you just need to specify comparing value as reversed order as:

final Map<String, Integer> sortedByCount = wordCounts.entrySet()
                .stream()
                .sorted((Map.Entry.<String, Integer>comparingByValue().reversed()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

The complete program for sorting in reverse order is:

public class SortMapByValueExample {
    public static Map<String, Integer> sortByValue(final Map<String, Integer> wordCounts) {

        return wordCounts.entrySet()
                .stream()
                .sorted((Map.Entry.<String, Integer>comparingByValue().reversed()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
    }

    public static void main(String[] args) {
        final Map<String, Integer> wordCounts = new HashMap<>();
        wordCounts.put("USA", 100);
        wordCounts.put("jobs", 200);
        wordCounts.put("software", 50);
        wordCounts.put("technology", 70);
        wordCounts.put("opportunity", 200);

        final Map<String, Integer> sortedByCount = sortByValue(wordCounts);

        System.out.println(sortedByCount);
    }
}

The output of the program is:

{jobs=200, opportunity=200, USA=100, technology=70, software=50}

 

You can see sorted() method takes Comparator as an argument, making it possible to sort a map with any kind of value. For example, the above sort can be written with comparator as:

public static Map<String, Integer> sortByValue(final Map<String, Integer> wordCounts) {

        return wordCounts.entrySet()
                .stream()
                .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
    }

 

You can implement Comparator with any kind of object. Isn't this cool feature?

Regex to match the IP Address
Java Lambda Expressions: Functions as First-Class Citizens