A quick example guide to Java 8 Optional filter() Method. filter(Predicate predicate) method used to return a Optional object for the given predicate(the condition).
Optional is a class and it is in java.util package. Optional is declared as final in its source code. Because no other classes can be inherited and to stop overriding the behavior.
First, let us take a look at syntax, it’s explanation, and example programs.
2. filter(Predicate predicate) Syntax
Below is the syntax for filter() method.
filter() method accepts Predicate as an argument and returns Optional value.
Predicate takes one argument and returns boolean. Checks for a condition and returns true if condition satisfies else false.
This checks for the condition employee salary > 10000.
3. Java 8 filter() Example for String
Below is the example program on filter() method.
In the example, first created an Optional instance by calling of() method with the string “Hello Mate, Welcome to java8example blog”.
Next, created a predicate welcomePredicate to validate if the string contains the “Welcome” word in it. After this, using filter(welcomePredicate) method and passed welcomePredicate as an argument. When the filter() method is executed, welcomePredicate is evaluated. If welcomePredicate is true then it returns the current string.
In the next example, Created another Predicate haiPredicate to validate if the string contains “Hai”. Again called the Optional filter(haiPredicate) and evaluated haiPredicate. But no “Hai” text found. Hence, the condition in haiPredicate is failed. So it returned empty optional instance. because of this, the output is printed as “Optional.empty”.
4. filter() Example but Passing List to Optional
In the above example, First created an Optional instance with String. In this example, Now we will create an Optional with List. We’ll see how
filter method behaves.
5. Internal Implementation
Below is the internal implementation code from java 12 API.
Internally, it calls predicate.test(value) method where test() is a functional method.
In this article, We’ve discussed Optional.filter() method with examples. filter() method takes Predicate as an argument and returns the Optional object if the Predicate condition is true.
This works the same for String, List, Map, or any object that Optional object is formed.
And also seen on how it works internally and what method is invoked to validate the predicate.
If we pass the predicate is null, it throws NullPointerException.