我在尝试对哈希映射进行排序并将其收集到List时遇到了这个答案:
Sort a Map<Key,>通过值
我试过了:
return myMap.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toList(Map.Entry::getKey, Map.Entry::getValue, (k,v) -> k, LinkedList::new));
但是,我得到这个错误:
Cannot resolve constructor 'LinkedList'
所有我想做的是收集我的键到一个列表后排序我的HashMap的值。我做错了什么?
您应该看到,Collectors.toList()
没有参数…所以,你有一个条目流,你想把条目映射到键,你应该使用map
。
myMap.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.map(Map.Entry::getKey)
.collect(Collectors.toList());
为什么不直接在排序后将条目映射到键?
return map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.map(Map.Entry::getKey) // stream of keys
.collect(Collectors.toList());