I have the following code
Random rnd = new Random();
rnd.ints().limit(100)
.filter(i-> i > 0)
.map(Math::sqrt)
.forEach(System.out::println)
Which generates the following compile error:
Streams.java:12: error: incompatible types: bad return type in method reference
.map(Math::sqrt)
^
double cannot be converted to int
If I use instead
.mapToDouble(Math::sqrt)
It works. The problem is that the compiler cannot infer the return type of the lambda expression used in map. Is there a way to specify it explicitly? I personally find the mapToxxx
set of functions clumsy.
This has nothing to do with "declaring the return type of your lambda." You're just specifying an invalid argument to map()
, and the compiler is telling you so.
The map
method in IntStream
takes an IntUnaryOperator
(a function from int
to int
). There is no method Math.sqrt
that can be converted to this signature.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With