Java OptionalDouble Class

Introduction

The OptionalDouble class in Java, part of the java.util package, is a container object which may or may not contain a double value. It is designed to handle optional primitive double values gracefully, avoiding NullPointerException and providing a more functional approach to dealing with optional values.

Table of Contents

  1. What is the OptionalDouble Class?
  2. Common Methods
  3. Examples of Using the OptionalDouble Class
  4. Conclusion

1. What is the OptionalDouble Class?

The OptionalDouble class provides a way to handle optional primitive double values in a functional and expressive manner. Instead of using null references, OptionalDouble encapsulates the presence or absence of a double value, making the code more readable and explicit in its intent.

2. Common Methods

  • empty(): Returns an empty OptionalDouble instance.
  • of(double value): Returns an OptionalDouble with the specified value present.
  • isPresent(): Returns true if there is a value present, otherwise false.
  • ifPresent(DoubleConsumer consumer): If a value is present, performs the given action with the value, otherwise does nothing.
  • getAsDouble(): If a value is present, returns the value, otherwise throws NoSuchElementException.
  • orElse(double other): Returns the value if present, otherwise returns other.
  • orElseGet(DoubleSupplier other): Returns the value if present, otherwise returns the result produced by the supplying function.
  • orElseThrow(): Returns the contained value if present, otherwise throws NoSuchElementException.
  • orElseThrow(Supplier<? extends X> exceptionSupplier): Returns the contained value if present, otherwise throws an exception provided by the exception supplier.

3. Examples of Using the OptionalDouble Class

Example 1: Creating an OptionalDouble

This example demonstrates how to create an OptionalDouble object with a value and an empty OptionalDouble.

import java.util.OptionalDouble;

public class OptionalDoubleExample {
    public static void main(String[] args) {
        OptionalDouble nonEmptyOptional = OptionalDouble.of(3.14);
        OptionalDouble emptyOptional = OptionalDouble.empty();

        System.out.println("Non-empty OptionalDouble: " + nonEmptyOptional);
        System.out.println("Empty OptionalDouble: " + emptyOptional);
    }
}

Output:

Non-empty OptionalDouble: OptionalDouble[3.14]
Empty OptionalDouble: OptionalDouble.empty

Example 2: Using isPresent and ifPresent

This example shows how to check if a value is present in an OptionalDouble and perform an action if it is.

import java.util.OptionalDouble;

public class OptionalDoubleCheckExample {
    public static void main(String[] args) {
        OptionalDouble optional = OptionalDouble.of(3.14);

        if (optional.isPresent()) {
            System.out.println("Value is present: " + optional.getAsDouble());
        }

        optional.ifPresent(value -> System.out.println("Value is present: " + value));
    }
}

Output:

Value is present: 3.14
Value is present: 3.14

Example 3: Using orElse and orElseGet

This example demonstrates how to provide a default value if the OptionalDouble is empty.

import java.util.OptionalDouble;

public class OptionalDoubleDefaultExample {
    public static void main(String[] args) {
        OptionalDouble optional = OptionalDouble.empty();

        double result1 = optional.orElse(0.0);
        double result2 = optional.orElseGet(() -> Math.random());

        System.out.println("Result using orElse: " + result1);
        System.out.println("Result using orElseGet: " + result2);
    }
}

Output:

Result using orElse: 0.0
Result using orElseGet: 0.85316653945304

Example 4: Using orElseThrow

This example shows how to throw an exception if the OptionalDouble is empty.

import java.util.OptionalDouble;

public class OptionalDoubleExceptionExample {
    public static void main(String[] args) {
        OptionalDouble optional = OptionalDouble.empty();

        try {
            double result = optional.orElseThrow(() -> new IllegalArgumentException("Value is not present"));
            System.out.println(result);
        } catch (IllegalArgumentException e) {
            System.out.println("Exception: " + e.getMessage());
        }
    }
}

Output:

Exception: Value is not present

Example 5: Using ifPresent with a DoubleConsumer

This example demonstrates how to use ifPresent with a DoubleConsumer to process the value if it is present.

import java.util.OptionalDouble;

public class OptionalDoubleConsumerExample {
    public static void main(String[] args) {
        OptionalDouble optional = OptionalDouble.of(3.14);

        optional.ifPresent(value -> System.out.println("Processing value: " + value));
    }
}

Output:

Processing value: 3.14

4. Conclusion

The OptionalDouble class in Java provides a powerful and expressive way to handle optional primitive double values. By using OptionalDouble, developers can avoid common pitfalls associated with null references and write more robust, readable, and error-free code. The examples provided demonstrate common usage patterns and highlight the capabilities of the OptionalDouble class.

Comments