Stream takeWhile / dropWhile
Take or drop elements from a stream based on a predicate.
Porównanie kodu
✕ 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)
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
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'.
Stare podejście
Manual Loop
Nowoczesne podejście
takeWhile/dropWhile
Od JDK
9
Poziom trudności
Początkujący
Wsparcie JDK
Stream takeWhile / dropWhile
Dostępne
Widely available since JDK 9 (Sept 2017)
Jak to działa
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.
Powiązana dokumentacja