Site Search:

Filter a collection by using lambda expressions

Back>

stream.filter()
stream.filter()


Since OCPJP have "Filter a collection by using lambda expressions" as a topic, they require testers to have proficiency on this topic.
Now official document about Stream.filter

Stream<T> filter(Predicate<? super T> predicate)
Returns a stream consisting of the elements of this stream that match the given predicate.This is an intermediate operation.
Parameters:
predicate - a non-interfering, stateless predicate to apply to each element to determine if it should be included
Returns:
the new stream

Let's take a look at more examples, do more exercises, no short cut for gaining proficiency.

OCPJP>cat FilterDemo.java
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Stream;

public class FilterDemo{
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
        Predicate<Integer> even = i -> i%2 == 0;
        stream.filter(even).forEach(System.out::println);
        System.out.println("======");
        Stream.iterate(0, i -> i+1).limit(6).filter(even.negate()).forEach(System.out::println);
    }
}
OCPJP>javac FilterDemo.java
OCPJP>java FilterDemo
2
4
6
======
1
3
5
OCPJP>

No more comments, these examples should be straight forward at this point.