CKTIS / Java
Stream.takeWhile: practical reference
Stream.takeWhile: practical reference: Stream.takeWhile(predicate) is a short-circuiting stateful intermediate operation; for an ordered stream it returns the longest matching prefix from the start.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
Stream.takeWhile(...)Stream.takeWhile(predicate) is a short-circuiting stateful intermediate operation; for an ordered stream it returns the longest matching prefix from the start.
Use it to read a header, data before a marker, or an increasing sequence until the first violation when encounter order matters.
It is not filter: after the first mismatch an ordered result excludes later matches; preserving the longest prefix can be costly in ordered parallel execution.
For an unordered stream where some but not all elements match, the result may be any matching subset, including empty; a null predicate causes NullPointerException.
takeWhile(n > 0) retains the initial 1 and 2, ends the result at 0, and excludes the later 3; exact stdout is [1, 2].
Examples
public class Main {
public static void main(String[] args) throws Exception {
var result = java.util.stream.Stream.of(1, 2, 0, 3).takeWhile(n -> n > 0).toList();
System.out.println(result);
}
}
Result
[1, 2]
takeWhile(n > 0) retains the initial 1 and 2, ends the result at 0, and excludes the later 3; exact stdout is [1, 2].