Java Optional get() Method
Example
Check that there is a value, and then get it:
import java.util.Optional;
public class Main {
public static void main(String[] args) {
Optional<String> name = Optional.of("Liam");
if (name.isPresent()) {
System.out.println(name.get());
}
}
}
Definition and Usage
The get() method returns the value in the Optional.
If the Optional is empty, it throws a NoSuchElementException and the program stops. Check with isPresent() first.
Tip: orElse() is often a better choice, because it never throws an exception. It returns a default value when the Optional is empty.
Syntax
public T get()
T refers to the data type of the value in the Optional.
Parameter Values
None.
Technical Details
| Returns: | The value in the Optional. |
|---|---|
| Throws: | NoSuchElementException - if the Optional is empty. |
Related Pages
Java Lambda Expressions Tutorial
❮ Optional Methods