Java Optional Methods
All Optional Methods
An Optional is like a box that either holds a value or is empty. A method can return an Optional instead of null, to show that the result can be missing.
Import java.util.Optional to use it. Create an Optional with of(), ofNullable() or empty(), and get the value with orElse(), which gives a default value when the box is empty. This way, your program does not crash with a NullPointerException.
| Method | Description | Return Type |
|---|---|---|
| empty() | Returns an empty Optional (an Optional with no value) | Optional<T> |
| filter() | Keeps the value only if it matches a condition, otherwise returns an empty Optional | Optional<T> |
| flatMap() | Changes the value with a function that returns an Optional, without putting an Optional inside another | Optional<U> |
| get() | Returns the value, or throws an exception if the Optional is empty | T |
| ifPresent() | Runs code with the value, only if there is a value | void |
| isPresent() | Checks if the Optional has a value | boolean |
| map() | Changes the value with a function and returns the result in a new Optional | Optional<U> |
| of() | Returns an Optional that holds the given value, which must not be null | Optional<T> |
| ofNullable() | Returns an Optional with the value, or an empty Optional if the value is null | Optional<T> |
| orElse() | Returns the value, or a default value if the Optional is empty | T |
| orElseGet() | Returns the value, or the result of a lambda expression if the Optional is empty | T |
| orElseThrow() | Returns the value, or throws an exception that you choose if the Optional is empty | T |
Related Pages
Java Lambda Expressions Tutorial