【问题标题】:Sorting a HashMap and collecting it to a list对 HashMap 进行排序并将其收集到列表中
【发布时间】:2021-11-11 18:32:38
【问题描述】:

我在尝试对哈希映射进行排序并将其收集到列表时遇到了这个答案:

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() 不接受任何参数。可能您会看到其他错误。 Alex 和 Efimov 的答案是正确的,只需使用 toList()

标签: java collections java-stream


【解决方案1】:

您应该看到Collectors.toList() 没有参数... 所以,你有条目流,你想将条目映射到键,你应该使用map

        myMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue())
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());

【讨论】:

  • 结果列表将被排序(列表将保持其插入顺序?)
  • 是的。结果列表将被排序(列表将保持其插入顺序)。
  • 您可以阅读以下内容了解更多详情:stackoverflow.com/q/29216588/9809131Some intermediate operations, such as sorted(), may impose an encounter order on an otherwise unordered stream
【解决方案2】:

为什么不在排序后将条目映射到键?

return map.entrySet()
            .stream()
            .sorted(Map.Entry.comparingByValue())
            .map(Map.Entry::getKey) // stream of keys
            .collect(Collectors.toList());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多