Comparator.comparing for Map.Entry in Java 8



给定以下代码:

@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方法,但我无法在这里解释问题。

这很有趣,

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

工程。

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

顺便说一句,这也适用于:

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

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

最新更新