Invoking toString via method reference in Java 8

我是研究僧i 提交于 2019-11-29 10:08:05

This has nothing to do with type erasure.

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 match the functional interface expected by the map() method. One is static with an int argument, and the other is the toString() method that overrides Object's toString().

The compiler doesn't know if you want to execute this :

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

or this :

Arrays.asList(1,2,3).stream().map(i->i.toString()).forEach(System.out::println);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!