【问题标题】:How to fix compiler issues while using Comparator.reversed()如何在使用 Comparator.reversed() 时修复编译器问题
【发布时间】: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


    【解决方案1】:

    以下格式对我有用:

    z = z.stream().sorted(Comparator.<AbstractMap.SimpleEntry<Integer, Double>>comparingDouble(entry -> entry.getValue()).reversed())
    

    我不确定为什么编译器无法推断Comparator 的类型。所以在上面的例子中我已经明确提到了类型。

    【讨论】:

      【解决方案2】:

      问题是编译器无法在第二种情况下推断类型,因为链式方法。你应该明确告诉它你想要什么。这应该有效:

      z = z.stream()
           .sorted(Comparator.<Map.Entry<Integer, Double>>comparingDouble(Map.Entry::getValue).reversed())
            .collect(Collectors.toList());
      

      我会这样做:

      z = z.stream()
           .sorted(Map.Entry.comparingByValue())
           .collect(Collectors.toList());
              
      z = z.stream()
           .sorted(Map.Entry.<Integer, Double>comparingByValue().reversed())
           .collect(Collectors.toList());
      

      除此之外,由于您正在修改初始变量,也许这会更好:

      z.sort(Map.Entry.<Integer, Double>comparingByValue().reversed());
      

      【讨论】:

      • Collections.reverseOrder(Map.Entry.comparingByValue()),不使用链式方法,所以类型推断有效。
      猜你喜欢
      • 2014-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-24
      • 1970-01-01
      • 2013-09-22
      相关资源
      最近更新 更多