对 HashMap 进行排序并将其收集到列表中
Sorting a HashMap and collecting it to a list
我在尝试对哈希映射进行排序并将其收集到列表时遇到了这个答案:
Sort a Map<Key, Value> by values
我试过这个:
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());
我在尝试对哈希映射进行排序并将其收集到列表时遇到了这个答案:
Sort a Map<Key, Value> by values
我试过这个:
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());