0

I came across this answer while trying to sort my hash map and collect it to a List:

Sort a Map<Key, Value> by values

I tried this:

return myMap.entrySet().stream()
        .sorted(Map.Entry.comparingByValue())
        .collect(Collectors.toList(Map.Entry::getKey, Map.Entry::getValue, (k,v) -> k, LinkedList::new));

However, I get this error:

Cannot resolve constructor 'LinkedList'

All I want to do is collect my keys into a list after sorting my HashMap by values. What am I doing wrong?

eaRobust
  • 87
  • 6
  • `Collectors.toList()` take no arguments. Probably you're seeing other error. Alex and Efimov answers are correct, just use `toList()` – OscarRyz Sep 16 '21 at 19:48

2 Answers2

1

There are no parameters for Collectors.toList() as you should see... So, you got stream of entries, you want map entries to keys, you should use map.

        myMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue())
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
Timur Efimov
  • 358
  • 2
  • 10
  • Resulted list will be sorted (the list will keep its insertion order?) – eaRobust Sep 16 '21 at 19:36
  • Yes. Resulted list will be sorted (the list will keep its insertion order). – Timur Efimov Sep 16 '21 at 19:40
  • 1
    You can read this for more details: https://stackoverflow.com/q/29216588/9809131 `Some intermediate operations, such as sorted(), may impose an encounter order on an otherwise unordered stream` – Timur Efimov Sep 16 '21 at 19:48
1

Why not just map the entry to key after sorting?

return map.entrySet()
            .stream()
            .sorted(Map.Entry.comparingByValue())
            .map(Map.Entry::getKey) // stream of keys
            .collect(Collectors.toList());
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42