In this source code example, we will demonstrate how to get the default value using the Optional orElseGet() method.
The orElseGet() method returns the value if present, otherwise invoke other and return the result of that invocation.
Java Optional orElseGet() Method Example
In the below example, orElseGet() method return default value because Optional contains 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(() -> "default@gmail.com");
System.out.println(defaultOptional2);
}
}
Output:
default@gmail.com
In the below example, orElse() method return actual value because Optional contains actual value:
import java.util.Optional;
public class OptionalDemo {
public static void main(String[] args) {
String email = "ramesh@gmail.com";
Optional<String> stringOptional = Optional.ofNullable(email);
String defaultOptional2 = stringOptional.orElseGet(() -> "default@gmail.com");
System.out.println(defaultOptional2);
}
}
Output:
ramesh@gmail.com
Related Optional Class Method Examples
- Create Optional Class Object in Java - empty(), of(), ofNullable() Methods
- Optional get() Method - Get Value from Optional Object in Java
- Optional isPresent() Method Example
- Optional orElse() Method Example
- Optional orElseGet() Method Example
- Optional orElseThrow() Method Example
- Optional filter() and map() Method Examples