Java Optional or()

In this guide, you will learn about the Optional or() method in Java programming and how to use it with an example.

1. Optional or() Method Overview


The or() method of the Optional class in Java returns an Optional describing the value of the current Optional, if a value is present; otherwise, returns an Optional produced by the supplying function.


public Optional<T> or(Supplier<? extends Optional<? extends T>> supplier)


- supplier: The supplier function that produces an Optional to be returned if the original Optional is empty.

Key Points:

- Introduced in Java 9.

- This method is used to provide a default or alternative Optional if the original Optional is empty.

- The supplying function is only invoked if the original Optional is empty.

- If the supplying function produces a null, a NullPointerException is thrown.

2. Optional or() Method Example

import java.util.Optional;

public class OptionalOrExample {

    public static void main(String[] args) {

        // Creating an Optional object with a value
        Optional<String> valuePresent = Optional.of("Hello World!");

        // Using or() when value is present
        Optional<String> result1 = valuePresent.or(() -> Optional.of("Default Value"));
        System.out.println(result1.get()); // Should print: Hello World!

        // Creating an empty Optional object
        Optional<String> valueAbsent = Optional.empty();

        // Using or() when value is absent
        Optional<String> result2 = valueAbsent.or(() -> Optional.of("Default Value"));
        System.out.println(result2.get()); // Should print: Default Value


Hello World!
Default Value


In the example, we have two Optional objects – valuePresent which holds a String value, and valueAbsent which is empty. 

We use the or() method on both objects. For valuePresent, the original Optional is returned as it has a value. For valueAbsent, the supplying function is invoked, creating a new Optional with the default value, showcasing how or() can be used to provide an alternative Optional in case the original one is empty.