โ— Shell
clean mode source โ†—

Stream takeWhile / dropWhile

Home / Streams / Stream takeWhile / dropWhile

Code Comparison

List<Integer> result = new ArrayList<>();
for (int n : sorted) {
    if (n >= 100) break;
    result.add(n);
}
// no stream equivalent in Java 8
var result = sorted.stream()
    .takeWhile(n -> n < 100)
    .toList();
// or: .dropWhile(n -> n < 10)

Why the modern way wins

๐ŸŽฏ

Short-circuit

Stops processing as soon as the predicate fails.

๐Ÿ”—

Pipeline-friendly

Chain with other stream operations naturally.

๐Ÿ“–

Declarative

takeWhile reads like English: 'take while less than 100'.

Modern Approach

takeWhile/dropWhile

JDK Support

Stream takeWhile / dropWhile

Available

Widely available since JDK 9 (Sept 2017)

How it works

takeWhile() returns elements while the predicate is true and stops at the first false. dropWhile() skips elements while true and returns the rest. Both work best on ordered streams.

Related Documentation

Proof