Java Streams filter() with Lambda Expressions

Examples of Java Stream’s filter() method to filter Java Collections and Handle Exceptions.

Overview

Java Stream’s API offers many helpful intermediate operations to process, filter, or manipulate elements in a Stream. The filter() method of Streams helps filter Stream elements based on specific criteria.

This article teaches how to use the filter() method along with Lambda Expressions and method references to filter out Stream elements. It also provides examples of handling exceptions inside a filter() method.

Java Streams filter() Method

The ‘filter(Predicate)‘ method, an Intermediate Operation of Java Streams, applies the Predicate to each element in the Stream and returns a new Stream of matching elements.

Stream<T> filter(Predicate<? super T> condition)
Code language: Java (java)

The Predicate function contains a condition it applies to the given element and returns a Boolean as an outcome. Given that the Predicate is a Functional Interface, we can use the filter() method with both a Method Reference or a Lambda Expression.

Using Java Streams filter() Method

To see an example of using the Java Streams filter() method along with a Lambda Expression, let’s create a custom class – Employee.

public class Employee { private final String name; private final Integer age; private final Boolean vaccinate; // Getters and Constructors }
Code language: Java (java)

Now, let’s make a Java List of dummy employees.

List<Employee> employees = List.of( new Employee("Janette X. Shenk", 45, true), new Employee("Geraldine Bean", 53, true), new Employee("Richard Knuckles", 55, false), new Employee("Lloyd Pinkerton", 52, false), new Employee("Louis McGriff", 42, false), new Employee("Amber Vang", 48, true) );
Code language: Java (java)

Java Stream Filter with Lambda Expression

Let’s use Java Stream’s filter() method with a Lambda Expression representing a Predicate.
Example of filtering a Java Stream with Lambda Expression.

List<Employee> output = employees.stream() .filter(e -> e.getAge() > 50) .toList(); output.forEach(System.out::println); //prints //Employee(name=Geraldine Bean, age=53, vaccinate=true) //Employee(name=Richard Knuckles, age=55, vaccinate=false) //Employee(name=Lloyd Pinkerton, age=52, vaccinate=false)
Code language: Java (java)

We used Stream’s filter() method on a Stream of Employee instances to get all the employees older than 50.

Java Stream Filter with Method Reference

As the Predicate is a functional interface, we can replace the Lambda Expression easily with a Method Reference.
Example of filtering a Stream using a Method Reference.

List<Employee> output = employees.stream() .filter(Employee::isVaccinated) .toList(); output.forEach(System.out::println); //prints //Employee(name=Janette X. Shenk, age=45, vaccinated=true) //Employee(name=Geraldine Bean, age=53, vaccinated=true) //Employee(name=Amber Vang, age=48, vaccinated=true)
Code language: Java (java)

We used the Stream filter() method to find vaccinated employees.

Java Stream Filter with Multiple Conditions

The previous two examples covered filtering a Java Stream using a single condition. Let’s quickly learn how to use the Stream filter() method with multiple conditions.
Example of filtering a Stream using Multiple Conditions.

List<Employee> output = employees.stream() .filter(e -> e.getAge() > 50 && e.isVaccinated()) .toList(); output.forEach(System.out::println); //prints //Employee(name=Geraldine Bean, age=53, vaccinated=true)
Code language: Java (java)

We used the Java Stream’s filter() method to get a List of Employee objects who are vaccinated and older than 50.

Handling Exceptions in Java Streams filter()

The Predicate method in Java doesn’t throw any checked exceptions. However, our Lambda Expression or a Method Reference may throw an Exception or two. Let’s understand ways to handle exceptions in Java Stream’s filter() method.

Firstly, let’s add a new method that throws an IOException in our Employee class.

public InputStream getPhoto() throws IOException { return new BufferedInputStream( new FileInputStream("/" + name + ".png")); }
Code language: Java (java)

If we use this method to filter our List of Employees, it results in a compilation error. That is because the Lambda Expression forces us to handle the exception.

List<Employee> output = employees.stream() .filter(e -> e.getPhoto() != null) .toList();
Code language: Java (java)

Using try/catch in Java Streams filter()

A simple way to handle exceptions within the Java Stream’s filter() method is to surround the method trowing method with a try/catch block.
Example of using try/catch block in Java Stream’s filter() method.

List<Employee> output = employees.stream() .filter(e -> { try { return e.getPhoto() != null; } catch (IOException ex) { return false; } }) .toList();
Code language: Java (java)

The Lambda Expression in the filter() method returns false when the method doesn’t return a photo, or the method throws an IOException.

Using Throwing Function in Java Streams filter()

Alternatively, we can use the ThrowingFunction library, an open-source library, to handle exceptions in the Stream filter() method. The ThrowingPredicate method provides the ‘unchecked()’ method that wraps the exception-throwing Predicate and catches exceptions.
Example of using Throwing Function to handle exceptions in Java Stream filter() method.

List<Employee> output = employees.stream() .filter(ThrowingPredicate .unchecked(e -> e.getPhoto() != null)) .toList();
Code language: Java (java)

Summary

This article provided a thorough introduction to Java Stream’s filter() method with the help of examples. The method applies the given Predicate on each element of a Stream and returns a new Stream containing only the matching elements of the first Stream.

We studied examples of using the filter() method with Lambda Expression, Method Reference, and multiple conditions to filter a Stream of elements based on various criteria. We also learned how to handle exceptions in the filter() method.

You can refer to our GitHub Repository for the complete source code of the examples used in this tutorial.