gpt4 book ai didi

java - Java 8 中 Map.Entry 的 Comparator.comparing

转载 作者:行者123 更新时间:2023-12-01 07:18:58 25 4
gpt4 key购买 nike

给出以下代码:

@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() 返回的内容)

关于java - Java 8 中 Map.Entry 的 Comparator.comparing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46904399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com