What is the Optional.orElse() method in Java?
In Java, the Optional object is a container object that may or may not contain a value. The Optional class is present in the java.util package.
You can read more about the
Optionalclass here.
What is the orElse() method of the Optional class?
The orElse() method will return the value present in an Optional object. If the value is not present, then the passed argument is returned.
public T orElse(T other)
Argument
The argument is the value to be returned if the Optional object is empty, i.e., there is no value present in the Optional object.
Return value
If the Optional object contains a value, then that value is returned. Otherwise, the passed argument is returned.
Code
The code below shows how to use the orElse() method.
import java.util.Optional;class OptionalOrElseExample {public static void main(String[] args) {Optional<Integer> optional1 = Optional.of(1);System.out.println("Optional1 : " + optional1);System.out.println("Value at Optional1 is : " + optional1.orElse(10));Optional<Integer> optional2 = Optional.empty();System.out.println("\nOptional2 : " + optional2);System.out.println("Value at Optional2 is : " + optional2.orElse(10));}}
Explanation
In the code above:
- In line 1, we imported the
Optionalclass.
import java.util.Optional;
- In line 5, we created an
Optionalobject of typeIntegerwith value1through theof()method.
Optional<Integer> optional1 = Optional.of(1);
- In line 7, we called the
orElse()method on theoptional1object with10as an argument. This method returns1because theoptional1object contains a value.
optional1.orElse(10); // 1
- In line 9, we used the
empty()method to get an emptyOptionalobject of theIntegertype. The returned object doesn’t have any value.
Optional<Integer> optional2 = Optional.empty();
- In line 11, we called the
orElse()method on theoptional2object with10as an argument. This method returns10because theoptional2object doesn’t contain any value.
optional2.orElse(10); // 10