Sort Java 8 Stream Map by Values: Get List of Keys

When working with Java 8 Streams, it is common to need to sort a Map by its values and return a list of the corresponding keys. Fortunately, this can be achieved quite easily using a combination of the Stream API and the Collections framework.

First, we need to create a Stream from the entrySet of the Map. We can then sort this Stream using the Comparator.comparingMap() method, which allows us to sort by the values of the Map. Finally, we can use the map() method to extract the keys from the sorted Stream and collect them into a List using the Collectors.toList() method.

Here's the code:


Map<String, Integer> map = new HashMap<>();
map.put("apple", 3);
map.put("banana", 2);
map.put("cherry", 1);

List<String> sortedKeys = map.entrySet().stream()
        .sorted(Map.Entry.comparingByValue())
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());

In this example, we have a Map with String keys and Integer values. We want to sort the Map by values and return a List of the corresponding keys. The resulting List will contain the keys in ascending order based on their corresponding values.

In summary, sorting a Java 8 Stream Map by its values and returning a list of the corresponding keys can be achieved using the Stream API and the Collections framework. By using the Comparator.comparingMap() method, we can easily sort the Stream by the values of the Map. We can then extract the keys from the sorted Stream and collect them into a List using the map() and Collectors.toList() methods.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

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

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information