Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

ParameterTypeDescription
predicatePredicate<? 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

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.

Thanks for reading!

Donate to the site — we work hard for you.