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.
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:
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 integersList<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 numbersl.stream().filter(num -> num % 2 == 0).forEach(System.out::println);}}
Free Resources