Program to sort the map by value using lambdas and streams in java 8

By | March 24, 2023

To sort a Map by value using lambdas and streams in Java 8, you can create a Stream of the map entries, sort them using the Comparator.comparing() method, and then collect them back into a LinkedHashMap.

Here’s an example code snippet that demonstrates this approach:

Map<String, Integer> unsortedMap = new HashMap<>();

unsortedMap.put(“John”, 75);

unsortedMap.put(“Mary”, 82);

unsortedMap.put(“Steve”, 65);

unsortedMap.put(“Bob”, 90);

Map<String, Integer> sortedMap = unsortedMap.entrySet().stream()


        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,

                (oldValue, newValue) -> oldValue, LinkedHashMap::new));

System.out.println(sortedMap); // Output: {Steve=65, John=75, Mary=82, Bob=90}

In the above example, we have an unsorted map unsortedMap with string keys and integer values. We first create a stream of the map entries using the entrySet() method, which returns a Set of key-value pairs. Then, we sort the stream of entries using the sorted() method and pass a lambda expression that uses the Map.Entry.comparingByValue() method to sort the entries by their values. Finally, we collect the sorted entries back into a LinkedHashMap using the Collectors.toMap() method, and pass a lambda expression to specify how to handle duplicate keys in case they exist.

The resulting sortedMap is a LinkedHashMap that contains the same key-value pairs as the original map, but the entries are sorted in ascending order based on their values

Leave a Reply

Your email address will not be published. Required fields are marked *