Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why stream average() method returns OptionalDouble instead of double?

Today when I was writing code using stream average, I got to know that stream average returns OptionalDouble instead of double. I know why OptionalDouble is used for.

What else can be returned when we call stream average so that we needed OptionalDouble?

An example will really be appreciated. Thanks in advance.

My code is given below:

OptionalDouble average = persons.stream()
            .mapToInt(person -> person.getAge())
            .average();
if(average.isPresent()) {
    System.out.println(average.getAsDouble());
}

Here persons is an ArrayList of Person class.

like image 530
Mukit09 Avatar asked Nov 28 '18 17:11

Mukit09


1 Answers

OptionalDouble is returned simply because the stream may be empty and it's a really good way to let the user decide what to do in the "no value" case i.e. you could provide an alternative value with orElse, perform another operation via ifPresent, throw an exception via orElseThrow etc.

like image 118
Ousmane D. Avatar answered Nov 15 '22 11:11

Ousmane D.