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.
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.
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