Sort Maps by Value in Java 8 [Snippet]
Want to learn more about how to sort maps by value in your Java application? Check out this code snippet to learn how in Java 8!
Join the DZone community and get the full member experience.
Join For FreeThe following demonstrates how to sort a given map based on the value using Java 8. One important thing to keep in mind is that you cannot sort a map in the Hashmap object.
map.entrySet().stream().sorted((o1, o2) -> o1.getValue().compareTo(o2.getValue())).map(e -> e.getKey()).collect(Collectors.toList()).forEach(k -> sortedMap.put(k, map.get(k)));
The full implementation of the code would look something like this:
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class C {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
map.put(“a”, 21);
map.put(“b”, 10);
map.put(“c”, 12);
map.put(“d”, 21);
map.entrySet().stream().sorted((o1, o2) -> o1.getValue().compareTo(o2.getValue())).map(e -> e.getKey()).collect(Collectors.toList()).forEach(k -> sortedMap.put(k, map.get(k)));
System.out.println(sortedMap);
}
}
Hope this is helpful!
Sort (Unix)
Java (programming language)
Opinions expressed by DZone contributors are their own.
Comments