Filtering Data with Java 8 Streams API: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
Line 44: Line 44:
Stream<T> skip​(long n);
Stream<T> skip​(long n);
</syntaxhighlight>
</syntaxhighlight>
skip() is a [[Functional_Programming#Stateful_Bounded|stateful bounded]] operation.


==Discarding Trailing Elements Based on the Evaluation of a Predicate==
==Discarding Trailing Elements Based on the Evaluation of a Predicate==

Latest revision as of 18:14, 29 March 2018

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);