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.
Stream<
T
> filter(Predicate
super T> predicate)
//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]
//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]