Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java 8

Java 8 filter

Educative Answers Team

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.

As described above, the filter() function takes the following two arguments as input:

  • condition: A condition in the form of a valid and defined function. This is a lambda function in most cases.

  • iterable: This is an iterable object (e.g. list, tuple, dictionary).

Returned: An iterator to the filtered items’ iterable object.

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.


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

svg viewer


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 -> num % 2 == 0).forEach(System.out::println); 


java 8
Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring