filter() method of Optional object in Java

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:

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:

filter() method of Optional object in Java

 

Add Comment