【发布时间】:2021-06-07 13:29:04
【问题描述】:
您应该如何在 Java 8 中按字段对对象列表进行排序?自然顺序可以正常工作,但反向顺序会引发编译器错误,指出您不能从静态上下文调用非静态方法。我猜测有问题的方法是 reversed() 而不是 getValue(),即使 IntelliJ 以红色突出显示 AbstractMap.SimpleEntry::getValue 而不是相反。
List<AbstractMap.SimpleEntry<Integer, Double>> z = new ArrayList<>();
for (int i = 0; i < 10; i++) {
z.add(new AbstractMap.SimpleEntry<>(i, new Random().nextDouble()));
}
// works
z = z.stream().sorted(Comparator.comparingDouble(AbstractMap.SimpleEntry::getValue)).collect(Collectors.toList());
// does not compile
z = z.stream().sorted(Comparator.comparingDouble(AbstractMap.SimpleEntry::getValue).reversed()).collect(Collectors.toList());
【问题讨论】:
标签: java sorting collections java-8 java-stream