Filtering Data with Java 8 Streams API
Internal
Overview
Filtering in this context means dropping certain elements based on a criterion.
All filtering methods are intermediate operations.
Methods
filter()
The most generic way to filter data in a stream is to apply a criterion, in form of a predicate. The filtering behavior is passed as a lambda expression predicate to the filter() method. The predicate will allow or exclude elements from the stream.
Stream<T> filter(Predicate<? super T> predicate);
distinct()
The Stream interface also exposes a distinct() method that filters out duplicates, retaining only the unique elements:
Stream<T> distinct();
The comparison is performed using the equals() method applied to the object flowing through the stream.
distinct() is a stateful unbounded operation.
Discarding Leading Elements Based on the Evaluation of a Predicate
Stream<T> dropWhile(Predicate<? super T> predicate);
Introduced in Java 9. To process: https://docs.oracle.com/javase/10/docs/api/java/util/stream/Stream.html#dropWhile(java.util.function.Predicate)
Discarding First n Elements
Stream<T> skip(long n);
skip() is a stateful bounded operation.
Discarding Trailing Elements Based on the Evaluation of a Predicate
Stream<T> takeWhile(Predicate<? super T> predicate);
Introduced in Java 9. To process: https://docs.oracle.com/javase/10/docs/api/java/util/stream/Stream.html#takeWhile(java.util.function.Predicate)
Truncating the Stream
Truncate the stream to contain no more than the given number of elements.
Stream<T> limit(long maxSize);