This method is used to check whether an Optional object is empty or not? If not, then do the operations with this object, otherwise do not do anything.
The parameter of this method is an object of the Consumer interface. You can see more about the Consumer interface here.
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package com.huongdanjava.javaexample; import java.util.Optional; public class Example { public static void main(String[] args) { String s = new String("Khanh"); Optional<String> opt = Optional.ofNullable(s); opt.ifPresent(x -> System.out.println(x)); } } |
Result: