This method first will check whether our Optional object is empty or not? If not, then continue to check whether its value meets a certain condition or not? If satisfied, it returns an Optional object containing this value, otherwise returns an empty Optional object.
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
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.filter(x -> x.contains("K")) .ifPresent(x -> System.out.println("Name: " + x)); } } |
In the above example, we used the Optional object’s filter() method to check if the string s contained the character “K”. If it contains, prints the whole string.
See more information about ifPresent() method of Optional object at here.
Result: