I have a method that builds a list and I want it to return the average of the list as an Optional value.
However, when I calculate the average value using Java 8, I always get the return value as an OptionalDouble.
How do I convert
OptionalDouble to Optional<Double>?
Below are my code for average calculation:
private static Optional<Double> averageListValue() {
// Build list
List<Double> testList = new ArrayList<>();
testList.add(...);
...
...
return testList.stream().mapToDouble(value -> value).average();
}
Thanks.
OptionalDouble help us to create an object which may or may not contain a double value. The getAsDouble() method returns value If a value is present in OptionalDouble object, otherwise throws NoSuchElementException. Syntax: public double getAsDouble() Parameters: This method accepts nothing.
Create an Optional with a non-null value -User user = new User("667290", "Rajeev Kumar Singh"); Optional<User> userOptional = Optional. of(user); If the argument supplied to Optional. of() is null, then it will throw a NullPointerException immediately and the Optional object won't be created.
I'd go for this approach:
private static Optional<Double> convert(OptionalDouble od) {
return od.isPresent() ?
Optional.of(od.getAsDouble()) : Optional.empty();
}
A slight variation on @Andremoniy's answer is to skip the DoubleStream
and use the averagingDouble()
collector:
if (testList.isEmpty()) {
return Optional.empty();
}
return Optional.of(testList.stream().collect(Collector.averagingDouble()));
Or consider whether 0 is a valid return value for an empty list, and possibly skip the Optional
entirely.
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