Java Optional ifPresent() Method
Example
Print a greeting only if there is a name:
import java.util.Optional;
public class Main {
public static void main(String[] args) {
Optional<String> name = Optional.of("Liam");
Optional<String> noName = Optional.empty();
name.ifPresent(n -> System.out.println("Hello " + n));
noName.ifPresent(n -> System.out.println("Hello " + n));
}
}
Definition and Usage
The ifPresent() method runs code with the value, but only if the Optional has a value. If it is empty, nothing happens.
You give it the code as a lambda expression (a short block of code that works like a method). The lambda gets the value as its parameter.
Syntax
public void ifPresent(Consumer<? super T> consumer)
T refers to the data type of the value in the Optional.
Parameter Values
| Parameter | Description |
|---|---|
| consumer | Required. A Consumer object or lambda expression that does something with the value. |
Related Pages
Java Lambda Expressions Tutorial
❮ Optional Methods