Optional ifPresent
Description
ifPresent(Consumer<? super T> action)
method
from the Optional class takes an action on the value contained in the Optional.
If the Optional is empty, this method does not do anything.
Example
The following code prints out the contents from Optional.
import java.util.Optional;
//from w ww . ja v a 2s. c o m
public class Main {
public static void main(String[] args) {
Optional<String> str = Optional.of("java2s.com");
str.ifPresent(value -> System.out.println("Optional contains " + value));
}
}
The code above generates the following result.
Note
If the Optional were empty, the code would not print anything.