Stream takeWhile / dropWhile
Take or drop elements from a stream based on a predicate.
Code Comparison
✕ Java 8
List<Integer> result = new ArrayList<>();
for (int n : sorted) {
if (n >= 100) break;
result.add(n);
}
// no stream equivalent in Java 8
✓ Java 9+
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'.
Old Approach
Manual Loop
Modern Approach
takeWhile/dropWhile
Since JDK
9
Difficulty
beginner
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.