Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort map by value using lambdas and streams

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: https://stackoverflow.com/a/109389/4315608

like image 786
Sudarsana Kasireddy Avatar asked Apr 10 '15 17:04

Sudarsana Kasireddy


People also ask

How do you sort a map using values?

Example: Sort a map by values Inside the method, we first created a list named capitalList from the map capitals . We then use the sort() method of Collections to sort elements of the list. The sort() method takes two parameters: list to be sorted and a comparator. In our case, the comparator is a lambda expression.

How do you sort a given HashMap on the basis of values?

If we need to sort the HashMap by values, we should create a Comparator. It compares two elements based on the values. After that get the Set of elements from the Map and convert Set into the List. Use the Collections.

How do you sort a map by both keys and value?

The idea is to put all data of HashMap into an ArrayList. Then extract all the keys of HashMap into an ArrayList. Next, sort the extracted keys using the Collections. sort() method, and then for each key extract its value using the get() method.


1 Answers

You can always start reading the documentation and some tutorials.

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

Reference

http://www.leveluplunch.com/java/examples/sort-order-map-by-values/

like image 154
ericbn Avatar answered Sep 18 '22 21:09

ericbn