Streams Początkujący

Take or drop elements from a stream based on a predicate.

✕ 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ć.
🎯

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
Stream takeWhile / dropWhile
Dostępne

Widely available since JDK 9 (Sept 2017)

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.

Udostępnij 𝕏 🦋 in