Sudarsana Kasireddy Sudarsana Kasireddy - 1 year ago 175
Java Question

Sort Map by value using java 8

I'm new to java 8, not sure how to use streams and it's methods to sort. If I have map as below, how to sort this map by value to take only top 10 entries using java 8.

HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 10);
map.put("b", 30);
map.put("c", 50);
map.put("d", 40);
map.put("e", 100);
map.put("f", 60);
map.put("g", 110);
map.put("h", 50);
map.put("i", 90);
map.put("k", 70);
map.put("L", 80);

I know before java 8, we can sort as this link

Answer Source

You can always start reading the documentation and some tutorials.

        .sorted(Map.Entry.<String, Integer>comparingByValue().reversed()) 
        .forEach(System.out::println); // or any other terminal method


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download