3

I have created following list

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

Scenario 1

This line does not work. shows compiler error

    System.out.println(list.stream()
            .sorted(Comparator.comparing(Math::abs).thenComparing(Integer::intValue))
            .collect(Collectors.toList()));
    

Scenario 2

But the below line work properly when we interchange the position of Math::abs and Integer::intValue

System.out.println(list.stream()
                .sorted(Comparator.comparing(Integer::intValue).thenComparing(Math::abs))
                .collect(Collectors.toList()));

Scenario 3

Also this line work properly when Math::abs is replaced by byAbs function object

Function<Integer, Integer> byAbs = Math::abs;

System.out.println(list.stream()
                .sorted(Comparator.comparing(byAbs).thenComparing(Integer::intValue))
                .collect(Collectors.toList()));

Scenario 4

This line also working fine when i replace Math::abs to (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

Again if I remove .thenComparing(Integer::intValue) from the Comparator it works fine.

System.out.println(list.stream()
                .sorted(Comparator.comparing(Math::abs))
                .collect(Collectors.toList()));

Compiler shows error on Comparator.comparing(Math::abs) and it states:

  • Cannot infer type argument(s) for <T, U> comparing(Function<? super T,? extends U>)
  • The type Math does not define abs(Object) that is applicable here

What is the actual logic behind it ?

1 Answers1

3

This is similar to the problem encountered by the compiler when resolving overloaded methods when using method references, as documented in http://openjdk.java.net/jeps/302 (section on Optional: Better disambiguation for functional expression).

This applies here because Math.abs has many overloads.

NightShade
  • 141
  • 1
  • 8