【问题标题】:Comparator.comparing for Map.Entry in Java 8 [duplicate]Java 8 中 Map.Entry 的 Comparator.comparing [重复]
【发布时间】:2017-10-24 07:16:25
【问题描述】:

给定以下代码:

@Test
public void test7() {
    Map<String, Integer> sortedData = new HashMap<>();
    sortedData.put("One", 1);
    sortedData.put("Two", 2);
    sortedData.put("Three", 3);

    Stream<Map.Entry<String, Integer>> stream = sortedData.entrySet().stream();
    List<String> sorted = stream
            .sorted(Comparator.comparing(Map.Entry::getValue))
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());
} 

编译成功,但是当我改变时

.sorted(Comparator.comparing(Map.Entry::getValue))

.sorted(Comparator.comparing(Map.Entry::getValue).reversed())

编译器抱怨Non static method can't be referenced in static context

我可以想象是因为getValue不是Map.Entry的静态方法,但是我在这里无法解释问题。

【问题讨论】:

    标签: java java-8 java-stream


    【解决方案1】:

    这很有趣,

    .sorted(Comparator.comparing(Map.Entry<String,Integer>::getValue).reversed ())
    

    有效。

    也许使用原始的Map.Entry 会使编译器感到困惑。

    顺便说一句,这也有效:

    .sorted(Collections.reverseOrder(Comparator.comparing(Map.Entry::getValue)))
    

    Collections.reverseOrder(this)reversed() 返回的内容)

    【讨论】:

    • 谢谢@eran。 IDEA IDE表明Map.Entry&lt;String,Integer&gt;::getValue)中的&lt;String,Integer&gt;是多余的,:-)
    • @Tom 真有趣
    • 目标类型推断不能通过方法调用链起作用,因此必须使用参数推断第一次调用的类型,因此需要Map.Entry&lt;String,Integer&gt;::getValue(Map.Entry&lt;String,Integer&gt; e) -&gt; e.getValue()。或者您将代码从调用链更改为嵌套调用:Collections.reverseOrder(Comparator.comparing(Map.Entry::getValue)) 或只是 Map.Entry.comparingByValue(Comparator.reverseOrder())...
    猜你喜欢
    • 2015-11-02
    • 2016-11-05
    • 2018-04-08
    • 1970-01-01
    • 2017-08-14
    • 2011-11-16
    • 2018-08-23
    • 2019-11-14
    • 1970-01-01
    相关资源
    最近更新 更多