Calling toString using method reference in Java 8

What am I missing? Why should I use Object::toString below and not Integer::toString ? Does this have anything to do with erasing styles with generics?

 Arrays.asList(1,2,3).stream().map(Integer::toString).forEach(System.out::println); //Won't compile Arrays.asList(1,2,3).stream().map(Object::toString).forEach(System.out::println); //Compiles and runs fine 
+6
source share
1 answer

This has nothing to do with erasing styles.

Look at the error message:

 (argument mismatch; invalid method reference reference to toString is ambiguous both method toString(int) in Integer and method toString() in Integer match) 

The Integer class has two toString methods that correspond to the functional interface expected by the map() method. One of them is static with an int argument, and the other is the toString() method, which overrides Object toString() .

The compiler does not know if you want to execute this:

 Arrays.asList(1,2,3).stream().map(i->Integer.toString(i)).forEach(System.out::println); 

or that:

 Arrays.asList(1,2,3).stream().map(i->i.toString()).forEach(System.out::println); 
+13
source

Source: https://habr.com/ru/post/980818/


All Articles