Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert OptionalDouble to Optional <java.lang.Double>

Tags:

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.

like image 520
000000000000000000000 Avatar asked Feb 13 '17 18:02

000000000000000000000


People also ask

What is OptionalDouble Java?

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.

How do you make an optional null in Java?

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.


2 Answers

I'd go for this approach:

private static Optional<Double> convert(OptionalDouble od) {
    return od.isPresent() ? 
        Optional.of(od.getAsDouble()) : Optional.empty();
}
like image 65
Marco13 Avatar answered Sep 20 '22 17:09

Marco13


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.

like image 37
shmosel Avatar answered Sep 19 '22 17:09

shmosel