Learnitweb

Java 8 filter() with examples

Java 8 Stream interface introduces filter() method which can be used to filter out elements based on a particular condition.

The condition to filter elements is specified as a predicate. If the condition evaluates to true, the object is selected. Otherwise, it will be ignored.

For example, you can use filter() to get even elements from an ArrayList.

The signature of the method is

Stream<T> filter(Predicate<? super T> predicate)

This method returns a stream consisting of the elements that matches the given predicate.

Since Predicate is a functional interface, you can pass a lambda expression as well to the filter().

The filter() method is an intermediate operation of the Stream interface and is lazy in nature, i.e. filter() produces another Stream and will not be evaluated until you call a terminal operation.

Now, we’ll see some examples of using filter() method.

Filter a Stream using Lambda Expression

In this example, we are filtering a list of Integers to find out even numbers and printing in Console.

import java.util.Arrays;
import java.util.List;
 
public class FilterExample {
    public static void main(String[] args) {
        //List to find even integers
    	List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
 
        //creating stream from list and filter 
    	list.stream()
            .filter(n -> n % 2 == 0)
            .forEach(System.out::println);
    }
}

Output

2
4
6
8
10

Filter a Stream using Predicate

In this Java Example, we are printing only even numbers from a stream. We are creating a Predicate to check if the number is even or not. Then, we are passing this Predicate to filter() method.

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
 
public class FilterExample {
    public static void main(String[] args) {
        //List to find even integers
    	List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
 
    	//Predicate to check if number is even
    	Predicate<Integer> predicateForEven = new Predicate<Integer>() 
        {
            @Override
            public boolean test(Integer n) {
                if (n % 2 == 0) {
                    return true;
                }
                return false;
            }
        };
    	
        list.stream().filter(predicateForEven).forEach(System.out::println);
    }
}

Output

2
4
6
8
10

Filtering a Stream and collecting result into a List

This Java example is same as the above examples, except we’ll collect the result into a list rather than printing in console. We can use the collect(Collectors.toList()) method to collect the stream of filtered elements into a List.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
 
public class FilterExample 
{
    public static void main(String[] args) 
    {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
 
        List<Integer> evenNumbers = list.stream()
                    .filter(n -> n % 2 == 0)
                    .collect(Collectors.toList());
         
        System.out.println(evenNumbers);
    }
}

Output

[2, 4, 6, 8, 10]

filter() with map() example

map() returns a stream consisting of the results of applying the given function to the elements of this stream. In this Java example, we’ll first get even numbers from a List and then will find square of numbers and will collect in a list.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
 
public class FilterWithMapExample 
{
    public static void main(String[] args) 
    {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
 
        List<Integer> evenWithSquare = list.stream()
                    .filter(n -> n % 2 == 0)
                    .map(n -> n * n)
                    .collect(Collectors.toList());
         
        System.out.println(evenWithSquare);
    }
}

Output

[4, 16, 36, 64, 100]