Java 8 sort map by value descending

Today, you will learn about the Java 8 sort map by value descending. We will cover different examples to sort map by keys, values and sorting in reverse order using Java 8 Stream API. Before we start, let’s discovery some methods which we are using in this tutorial, below:

Stream.sorted() – Sort elements base on Comparator.
comparingByKey() – Returns a comparator that compares Map.Entry in natural order on key.
Sort key in reversed order
comparingByKey() – Returns a comparator that compares Map.Entry in natural order on key.
comparingByKey().reversed() – Returns a comparator that imposes the reverse ordering of this comparator.
Sort by value
comparingByValue() – Returns a comparator that compares Map.Entry in natural order on value.
Apply limit
comparingByKey() – Returns a comparator that compares Map.Entry in natural order on key.
comparingByKey().reversed() – Returns a comparator that imposes the reverse ordering of this comparator.
forEachOrdered() – Print the result with order.

Sort Map by Keys
Here, we’re using the method Map.Entry.comparingByKey() to sort a map by keys and return a new LinkedHashMap, we need LinkedHashMap to keep the order. toMap() method will returns HashMap by default so we need to pass the reference method LinkedHashMap::new to force it returns a LinkedHashMap.

Output

Sort Map by Values

Here, we’re using the method Map.Entry.comparingByValue() to sort a map by values

Output
Java 8 sort map by value descending

That’s all about the Java 8 sort map by value descending.

References
Map.Entry (Java Platform SE 8 )

Download the complete source code, click link below

SortMapExample.zip (5 downloads)

Leave a Comment

*

Please share it if you found this useful
Hide Buttons