I’m using this code but eclipse shows an error saying
stream() is undefined for the type OptionalDouble
The error shown by eclipse is
- The method stream() is undefined for the type OptionalDouble .
My code is something like this
return IntStream.of(1,2,3,4,5,6)
.asLongStream()
.flatMap(a -> a)
.average()
.stream()
.mapToLong(Math::round)
.mapToInt(i -> (int) i)
.findFirst()
.orElse(-1);
I tried average().getasDouble() but that also didn’t work. How do i fix the code ?
I can do one thing Double d=average().getasDouble() then apply Math.round(d) seperately.
Is it possible to fix the code after average().stream() in functional way without error ?
When average() return OptionalDouble and that can’t be streamed by stream() , how do you go about it ?
>Solution :
OptionalDouble.stream has existed ever since Java 9. You should check your Java version.
If you are unable to use a newer version of Java for some reason, you can implement stream yourself as a static helper method. What it does is very simple.
public static DoubleStream streamOfOptional(OptionalDouble d) {
return d.isEmpty() ? DoubleStream.empty() : DoubleStream.of(d.getAsDouble());
}
return streamOfOptional(
IntStream.of(1,2,3,4,5,6)
.average()
)
.mapToLong(Math::round)
.mapToInt(i -> (int) i)
.findFirst()
.orElse(-1);