Home » Java » Core Java » Java 8 Optional filter()

About Venkatesh Nukala

Venkatesh Nukala
Venkatesh Nukala is a Software Engineer working for Online Payments Industry Leading company. In my free time, I would love to spend time with family and write articles on technical blogs. More on JavaProgramTo.com

Java 8 Optional filter()

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).

1. Overview

In this tutorial, We’ll discuss how to use Predicate with Optional class. The
Java 8 Optional class has a method filter() which takes  Predicate as an argument.

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.

API Note: If a value is present, and the value matches the given predicate, returns an Optional describing the value, otherwise returns an empty Optional.

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.

1
public Optional<T> filter(Predicate<? super T> predicate)

filter() method accepts Predicate as an argument and returns Optional value.

Predicate Example:

Predicate takes one argument and returns boolean. Checks for a condition and returns true if condition satisfies else false.

1
Predicate<Employee> empSal = e -> e.getSal() > 10000;

This checks for the condition employee  salary &gt; 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”.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.java.w3schools.blog.java8.optional;
 
import java.util.Optional;
import java.util.function.Predicate;
 
/**
 * java 8 Optional filter() method example
 *
 * @author Venkatesh
 *
 */
public class OptionalFilterExample {
  
 public static void main(String[] args) {
   
  Optional<String> helloOptonal = Optional.of("Hello Mate, Welcome to java8example blog");
   
  // Predicate match case
  Predicate<String> welcomePredicate = s -> s.contains("Welcome");
  Optional<String> welcomeOptional = helloOptonal.filter(welcomePredicate);
  System.out.println("welcomeOptional : " + welcomeOptional);
   
  // Predicate non-match case
  Predicate<String> haiPredicate = s -> s.contains("Hai");
  Optional<String> haiOptional = helloOptonal.filter(haiPredicate);
  System.out.println("haiOptional : " + haiOptional);
 }
}

Output:

1
2
welcomeOptional : Optional[Hello Mate, Welcome to java8example blog]
haiOptional : 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.

1
2
3
4
5
6
7
List<String> countries = Arrays.asList("USA", "UK", "AUS");
Optional<List<String>> countriesOptional = Optional.of(countries);
 
Predicate<List<String>> listPredicate = list -> list.stream().filter(name -> name.startsWith("U")).count() > 0;
 
Optional listOpional = countriesOptional.filter(listPredicate);
System.out.println("List Optional filter() : "+listOpional);

Output:

1
List Optional filter() : Optional[[USA, UK, AUS]]

5. Internal Implementation

Below is the internal implementation code from java 12 API.

1
2
3
4
5
6
7
8
public Optional<T> filter(Predicate<? super T> predicate) {
    Objects.requireNonNull(predicate);
    if (!isPresent()) {
        return this;
    } else {
        return predicate.test(value) ? this : empty();
    }
}

Internally, it calls predicate.test(value) method where test() is a functional method.

6. Conclusion

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.

Full example code on GitHub

API Ref

Published on Java Code Geeks with permission by Venkatesh Nukala, partner at our JCG program. See the original article here: Java 8 Optional filter()

Opinions expressed by Java Code Geeks contributors are their own.

(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments