Java 8 filter

The Java 8 Stream interface has a filter() method which filters out elements from a collection based on a given condition. This condition must be specified as a predicate which is passed on to the filter() method.

svg viewer

filter() does not actually perform any filtering; instead, it creates a new stream that contains the elements of the initial stream which match the given predicate.

Syntax

The method definition of the Java 8 filter is shown below:

svg viewer

Code

The code snippet below illustrates the usage of the Java 8 filter:

import java.util.*;
class FilterDemo {
public static void main(String[] args)
{
// list of integers
List<Integer> l = Arrays.asList(3, 4, 6, 12, 20, 21, 27, 30);
// Using Stream filter to filter out the odd numbers
// i.e predicate must be a method that is true for even numbers
l.stream().filter(num -> num % 2 == 0).forEach(System.out::println);
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved