Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot Stream average() undefined for OptionalDouble

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading