我已经创建了以下列表
List<Integer> list = Arrays.asList(4, 5, -2, 0, -3, -1, -5, -4);Scenario 1
这一行不起作用。显示编译器错误
System.out.println(list.stream()
.sorted(Comparator.comparing(Math::abs).thenComparing(Integer::intValue))
.collect(Collectors.toList()));Scenario 2
但是,当我们交换Math::abs和Integer::intValue的位置时,下面的线正常工作。
System.out.println(list.stream()
.sorted(Comparator.comparing(Integer::intValue).thenComparing(Math::abs))
.collect(Collectors.toList()));Scenario 3
另外,当Math::abs被byAbs函数对象替换时,这一行正常工作。
Function<Integer, Integer> byAbs = Math::abs;
System.out.println(list.stream()
.sorted(Comparator.comparing(byAbs).thenComparing(Integer::intValue))
.collect(Collectors.toList()));Scenario 4
当我将Math::abs替换为(Integer x)-> Math.abs(x)时,这一行也可以正常工作。
System.out.println(list.stream()
.sorted(Comparator.comparing((Integer x)-> Math.abs(x)).thenComparing(Integer::intValue))
.collect(Collectors.toList()));Scenario 5
同样,如果我从比较器中删除.thenComparing(Integer::intValue),它也可以正常工作。
System.out.println(list.stream()
.sorted(Comparator.comparing(Math::abs))
.collect(Collectors.toList()));编译器在Comparator.comparing(Math::abs)上显示错误,它声明:
的abs(Object)
它背后的实际逻辑是什么?
发布于 2021-02-20 15:05:45
这类似于编译器在使用方法引用时解析重载方法时遇到的问题,如http://openjdk.java.net/jeps/302 (关于可选部分:更好地消除函数表达式的歧义)。
这在这里适用,因为Math.abs有许多重载。
https://stackoverflow.com/questions/66292705
复制相似问题