Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 stream map to list of keys sorted by values

I have map Map<Type, Long> countByType and I want to have a list which has sorted (min to max) keys by their corresponding values. My try is:

countByType.entrySet().stream().sorted().collect(Collectors.toList()); 

however this just gives me a list of entries, how can I get a list of types, without losing the order?

like image 606
adaPlease Avatar asked May 24 '15 16:05

adaPlease


People also ask

Can map be sorted on values?

A map is not meant to be sorted, but accessed fast. Object equal values break the constraint of the map. Use the entry set, like List<Map.


2 Answers

You have to sort with a custom comparator based on the value of the entry. Then select all the keys before collecting

countByType.entrySet()            .stream()            .sorted((e1, e2) -> e1.getValue().compareTo(e2.getValue())) // custom Comparator            .map(e -> e.getKey())            .collect(Collectors.toList()); 
like image 34
Sotirios Delimanolis Avatar answered Sep 16 '22 18:09

Sotirios Delimanolis


You say you want to sort by value, but you don't have that in your code. Pass a lambda (or method reference) to sorted to tell it how you want to sort.

And you want to get the keys; use map to transform entries to keys.

List<Type> types = countByType.entrySet().stream()         .sorted(Comparator.comparing(Map.Entry::getValue))         .map(Map.Entry::getKey)         .collect(Collectors.toList()); 
like image 190
Jesper Avatar answered Sep 20 '22 18:09

Jesper