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.