Java 8中的Comparator.cominging为Map.Entry

Tom*_*Tom 0 java java-8 java-stream

给定以下代码:

@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());
} 
Run Code Online (Sandbox Code Playgroud)

它可以成功编译,但是当我更改时

.sorted(Comparator.comparing(Map.Entry::getValue))
Run Code Online (Sandbox Code Playgroud)

.sorted(Comparator.comparing(Map.Entry::getValue).reversed())
Run Code Online (Sandbox Code Playgroud)

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

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

Era*_*ran 6

这真有趣,

.sorted(Comparator.comparing(Map.Entry<String,Integer>::getValue).reversed ())
Run Code Online (Sandbox Code Playgroud)

作品。

也许使用raw Map.Entry会使编译器混乱。

顺便说一句,这也适用:

.sorted(Collections.reverseOrder(Comparator.comparing(Map.Entry::getValue)))
Run Code Online (Sandbox Code Playgroud)

(返回的Collections.reverseOrder(this)是什么reversed()