filter() Method Example In Java

The stream filter() method provides the functionality to filter stream's elements on the basis of given lambda expression or predicate. The stream filter() method expects a lambda expression or predicate in argument and the lambda expression returns a boolean(true/false) value, based on boolean value filter method filters the elements.

  1. filter() is an intermediate stream operation.
  2. filter method expects a lambda expression or predicate in argument.
  3. The Predicate. is a functional interface. So, you can also pass lambda expression here.
  4. filter() method does not change/modify the original source/collection.
  5. filter() method creates a new collection(list/array) based on the condition and returns the new collection.
  6. Stream does not modify the source. It produces a new Stream by filtering or applying any logic.

Syntax:

Stream<T> filter(Predicate predicate) 

Example of filterig data using Lambda Expression in arguments

//Importing required classes
import java.util.*;
import java.io.*;
import java.util.stream.*;

public class FilterExample {
  static void main ( String args[]) {

  Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
  //Filtering the even numbers from a collection
  List<Integer> evenList = 
    Arrays.asList(numbers)
        .stream()
        //passing lambda expression in argument
        .filter(i -> i % 2 == 0)
        .collect(Collectors.toList());            
    System.out.println( "Filtered even numbers : "+ evenList );
 }
}

Output:
    Filtered even numbers : [2, 4, 6, 8, 10, 12]

Example of filterig with Predicate argument:

//Importing required classes for stream
import java.util.*;
import java.io.*;
import java.util.stream.*;

public class PredicateFilterExample
   static void main ( String args[] ){
     //Creating predicate
     Predicate<Integer> pr = i -> ( i % 2 == 0 );
     Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8 };

     //Filtering the even numbers from a collection
     List<Integer> evenList = 
        Arrays.asList(numbers)
        .stream()
        //passing predicate in argument
        .filter(pr)
        .collect(Collectors.toList());
               
      System.out.println( "Filtered even numbers : "+ evenList );
  }
}

Output:
    Filtered even numbers : [2, 4, 6, 8]