Java 为什么方法引用在场景1中显示编译器错误,但在场景2中有效?

Java 为什么方法引用在场景1中显示编译器错误,但在场景2中有效?,java,lambda,functional-programming,java-stream,comparator,Java,Lambda,Functional Programming,Java Stream,Comparator,我创建了以下列表 List<Integer> list = Arrays.asList(4, 5, -2, 0, -3, -1, -5, -4); 场景2 但是当我们交换Math::abs和Integer::intValue System.out.println(list.stream() .sorted(Comparator.comparing(Integer::intValue).thenComparing(Math::abs))

我创建了以下列表

   List<Integer> list = Arrays.asList(4, 5, -2, 0, -3, -1, -5, -4);
    
场景2

但是当我们交换
Math::abs
Integer::intValue

System.out.println(list.stream()
                .sorted(Comparator.comparing(Integer::intValue).thenComparing(Math::abs))
                .collect(Collectors.toList()));
场景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()));
场景5

同样,如果我从比较器中删除
。然后比较(Integer::intValue)
,它工作正常

System.out.println(list.stream()
                .sorted(Comparator.comparing(Math::abs))
                .collect(Collectors.toList()));
编译器在比较器上显示错误。比较(Math::abs)并声明:


  • 无法推断用于比较的类型参数(Function这类似于编译器在使用方法引用解析重载方法时遇到的问题,如(可选:函数表达式的更好消歧部分)中所述


    这适用于这里,因为
    Math.abs
    有许多重载。

    可能是我的一个副本添加了下一个场景,即场景2,当我们交换Math::abs和Integer::value的位置时,它实际起作用。@arvindkumaravinash如果是这样,那么它也必须在场景2中起作用,但它起作用。@NightShade
    System.out.println(list.stream()
                .sorted(Comparator.comparing((Integer x)-> Math.abs(x)).thenComparing(Integer::intValue))
                .collect(Collectors.toList()));
    
    System.out.println(list.stream()
                    .sorted(Comparator.comparing(Math::abs))
                    .collect(Collectors.toList()));