Sort a Map using Stream and Collectors in Java

In this tutorial, I will show you how to order elements in a Map object using the Stream object and the Collectors object in Java by key and by value.

For example, we have a Map object like this:

Prior to Java 8, to sort the elements of this Map object by key, we could use the Collections.sort() static method of the Collections class:

Result:

Sort a Map using Stream and Collectors in Java

Do the same if you want to use the sort() static method of the Collections class to sort the elements in the Map object by value.



From Java 8 onwards, you have another way to use the Stream object with the Collectors object.

We will create a new Stream object from the Map object and then use the sorted() and collect() methods of this Stream object to sort.

For example, we need to order the elements of the Map object by key, we will code as follows:

Here, the sorted() method acts as an intermediate operation in the Stream pipeline. The parameter of this method is a Comparator object that allows us to define what criteria to sort. You can also use the static comparingByKey() method of the Map.Entry class to sort by key as follows:

The collect() method will act as a terminal operation in the Stream pipeline. The parameter of this method is a Collectors object and we will use the Collectors object’s toMap() method to construct a new Map object after sorting.

The Collectors object’s toMap() method has some overload methods:

Where the first and second parameters of the toMap() method are instances of the Function interface used to generate keys and values for the new Map object.

The third parameter of the toMap() method is an optional parameter that is used in case the key of the new Map object has duplicate values. Using the BinaryOperator object, we can select the value of these duplicate keys, avoiding the IllegalStateException. In the above example, (oldValue, newValue) -> oldValue means that in case the key is duplicated, we will get the value of the previous key.

The final parameter of the toMap() method is also an optional parameter, which allows us to define a new Map object as a class instance. By default, if you do not use this parameter, then the class will be HashMap.

The result of this example is as follows:

Sort a Map using Stream and Collectors in Java

To order elements in a Map object by value, we can use the static comparingByValue() method of the Map.Entry object:

Here, I use the reverseOrder() static method of the Comparator class to sort these values descending.

Result:

Sort a Map using Stream and Collectors in Java

 

Add Comment