Stream.dropWhile()
Drops elements while a condition holds and passes on everything after.
Available since: Java 9
Syntax
default Stream<T> dropWhile(Predicate<? super T> predicate)Parameters
| Parameter | Type | Description |
|---|---|---|
| predicate | Predicate<? super T> | While this condition is true, elements are dropped. |
Return value
Stream<T>The rest of the stream from the first element that fails the condition.
Examples
Skipping header lines:
void main() {
List<String> lines = List.of("# title", "# author", "first line", "# not a header", "last line");
lines.stream()
.dropWhile(l -> l.startsWith("#"))
.forEach(IO::println);
}Output:
first line
# not a header
last lineNotes
After the first non-matching element the condition is not checked any more — that is why the # not a header line stayed. It is the mirror counterpart of takeWhile().
See also
- Stream.takeWhile() — Takes elements while a condition holds and stops at the first one that fails it.
- Stream.skip() — Skips the first N elements of a stream.
In the tutorial
- Stream operations — The main Stream API operations — filter, map, sorted, distinct, limit, skip, count, reduce, anyMatch, findFirst and numeric streams.