Simple and easy-to-understand examples of sorting Map by values, using Java 8 Stream APIs, in ascending and descending (reverse) orders. At the center of logic is the method Map.Entry.comparingByValue(), which compares the map entries in the natural order by entry values.
1. Map.Entry.comparingByValue()
In Java 8, Map.Entry
class has a static method comparingByValue() to help sort a Map by values. It returns a Comparator that compares Map.Entry
in the natural order of values.
map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
...
Alternatively, we can pass a custom Comparator to sort the values in a custom order. For example, we can use Comparator.reverseOrder() to sort the map in reverse order.
map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
...
2. Java Program to Sort a Map by Values
2.1. Ascending Order or Natural Order
The following java program sorts the entries of a Map in the natural order and collects the sorted entries in a LinkedHashMap. We are collecting the entries in LinkedHashMap because it maintains the insertion order.
Map<String, Integer> unsortedMap = Map.of("a", 1, "c", 3, "b", 2, "e", 5, "d", 4);
LinkedHashMap<String, Integer> sortedMap = unsortedMap.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
System.out.println(sortedMap);
The program output.
{a=1, b=2, c=3, d=4, e=5}
2.2. Descending Order
As discussed above, we use Comparator.reverseOrder() to sorting the Map values in reverse order.
Map<String, Integer> unsortedMap = Map.of("a", 1, "c", 3, "b", 2, "e", 5, "d", 4);
LinkedHashMap<String, Integer> sortedMap = unsortedMap.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
System.out.println(sortedMap);
The program output.
{e=5, d=4, c=3, b=2, a=1}
Happy Learning !!
Leave a Reply