Stream.takeWhile()
Takes elements while a condition holds and stops at the first one that fails it.
Available since: Java 9
Syntax
default Stream<T> takeWhile(Predicate<? super T> predicate)Parameters
| Parameter | Type | Description |
|---|---|---|
| predicate | Predicate<? super T> | The condition to continue. |
Return value
Stream<T>The start of the stream up to the first element that fails the condition.
Examples
The difference from filter():
void main() {
List<Integer> nums = List.of(1, 2, 3, 10, 4, 5);
IO.println(nums.stream().takeWhile(n -> n < 5).toList());
IO.println(nums.stream().filter(n -> n < 5).toList());
}Output:
[1, 2, 3]
[1, 2, 3, 4]Notes
filter() checks every element, while takeWhile() stops at the first false. That makes takeWhile() suitable for infinite and sorted streams. On an unordered stream the result is unpredictable.
See also
- Stream.dropWhile() — Drops elements while a condition holds and passes on everything after.
- Stream.filter() — Keeps only the stream elements that match a condition.
- Stream.limit() — Truncates a stream to its first N elements.
Related recipes
In the tutorial
- Stream operations — The main Stream API operations — filter, map, sorted, distinct, limit, skip, count, reduce, anyMatch, findFirst and numeric streams.