{

Java8 - OptionalDouble class Example


java8 - Top 10 Optional Class Examples

What is java.util.OptionalDouble in java?

OptionalDouble class is introduced in java8.

This is Optional container for double values that may contains empty or non empty values. if double value is present, isPresent() method returns true, and getAsDouble() method returns double value.

OptionalDouble is a primitive double version of the Optional class whereas Optional is an Optional class for Double Object.

OptionalDouble class Example

This is an usage of isPresent(), getAsDouble(), orElse() and Lambda expressions example.

  • Created OptionalDouble using static of() method
  • Check double value exists or not using isPresent()method
  • getAsDouble() method returns double value from an object.
  • orElse() returned value if exists, return other
  • ifPresent() method takes DoubleConsumer if value exists, else nothing.
  • public static void main(String[] args) { OptionalDouble optionalDouble = OptionalDouble.of(12.0); System.out.println(optionalDouble.isPresent()); // true System.out.println(optionalDouble.getAsDouble()); //12.0 System.out.println(optionalDouble.orElse(12.0));//12.0 optionalDouble.ifPresent(System.out::println);//12.0 optionalDouble.ifPresent((value) -> System.out.println(value));//12.0 } }
The output of the above code execution is  

```markup
true  
12.0  
12.0  
12.0  
12.0  

How to convert Double to OptionalDouble in java?

OptionalDouble of() method used to create OptionalDouble with non empty values.
Syntax is
public static OptionalDouble of(double value)

This takes double Value as input and returns OptionalDouble object.

import java.util.OptionalDouble;
public class Test {
    public static void main(String[] args) {
        double doubleValue = 14.3;
        OptionalDouble optionDouble = OptionalDouble.of(doubleValue);
        System.out.println(optionDouble.isPresent()); // returns true  
    }
}  

How to convert OptionalDouble to double in java8?

getAsDouble() method is used to convert from OptionalDouble to double value

import java.util.OptionalDouble;
public class Test {
    public static void main(String[] args) {
        double doubleValue=0;
        OptionalDouble optionDouble = OptionalDouble.of(37.8);
        if(optionDouble.isPresent()) {
            doubleValue=optionDouble.getAsDouble();
        }
        System.out.println(doubleValue);
    }
}  

Find an Average of an array of numbers using OptionalDouble Example

This is an example of finding the average of an array of numbers in java8.

IntStream is a sequential class used to process primitive numbers with support parallel aggregation operations.

It has average() which returns OptionalDouble class. The below example uses OptionalDouble.isPresent and getAsDouble method usage a with lambda expression.

import java.util.Arrays;
import java.util.OptionalDouble;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Test {
    public static void main(String[] args) {
        Integer[] numbersArray = {1,2,3,4,5,6,7};
        Stream<Integer> streamIntegers = Arrays.stream(numbersArray);
        IntStream intStreamNumber = streamIntegers.mapToInt(value -> value);
        OptionalDouble numberAverage = intStreamNumber.average();
        System.out.println(numberAverage.isPresent() ?
                "Numbers Average = " + numberAverage.getAsDouble() :
                "Empty Array");
    }
}  
Numbers Average = 4.0

Difference between OptionalDouble and Optional in java8?

Optional<Double> get() method returns Double Object
OptionalDouble.getAsDouble() method returns double primitive value
DoubleStream and OptionalDouble objects of double value might result nullpointerexception
Optional<Double> and Stream<Double> for double value added extra wrapper to avoid null exceptions.

OptionalDouble Methods

An optional double class has many utility methods to test values are available or not available.

Method Description
empty() Creating Empty OptionalDouble Instance
getAsDouble() Return double value, if value exists in OptionDouble, Else NoSuchElementException
ifPresent(DoubleConsumer consumer) Executes DoubleConsumer, if value exists in OptionDouble, else do nothing
isPresent() Returns true, if value exists in OptionDouble, else returns false
of(Double double) Creation of OptionalDouble with non null values, if null is passed, NullPointerException thrown and OptionDouble object will not be initialized
orElse(double other) Return default value if value is not presented in OptionalDouble
orElseGet(DoubleSupplier other) Returns value if value presented in OptionalDouble, else supplier is being called and result this will be returned
orElseThrow(Supplier exceptionSupplier) Returns value if value presented in OptionalDouble, else supplier is being called and throws an error

Conclusion

In this tutorial, Learned about OptionalDouble class in java

  • multiple conversion examples
  • Difference between OptionalDouble and Optional in java8
  • OptionalDouble Methods
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.