Optional orElseGet Method

In this tutorial, we will demonstrate how to get the default value using the Optional orElseGet() method.

The orElseGet() method returns the value if present, otherwise returns the result of that invocation.

Java Optional orElseGet() Method Example

In the below example, orElseGet() method returns the default value because Optional contains a null value:

import java.util.Optional;

public class OptionalDemo {
    public static void main(String[] args) {

        String email = null;
        Optional<String> stringOptional = Optional.ofNullable(email);
        String defaultOptional2 = stringOptional.orElseGet(() -> "[email protected]");
        System.out.println(defaultOptional2);
    }
}
Output:
default@gmail.com
In the below example, the orElseGet() method returns the actual value because Optional contains an actual value:
import java.util.Optional;

public class OptionalDemo {
    public static void main(String[] args) {

        String email = "[email protected]";
        Optional<String> stringOptional = Optional.ofNullable(email);
        String defaultOptional2 = stringOptional.orElseGet(() -> "[email protected]");
        System.out.println(defaultOptional2);
    }
}

Comments