GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • java.evolved
  • ←
  • →

This view

  • Original page
  • New address

GeezerVison is showing javaevolved.dev — Stream takeWhile / dropWhile | java.evolved

Home / Streams / Stream takeWhile / dropWhile
Streams Beginner

Stream takeWhile / dropWhile

  • 🐛 Report a code issue
  • 🌐 Report a translation issue
  • 💡 Suggest a new pattern

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

Streams API
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)
Share 𝕏
See a problem with this code? Let us know.
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.

Related Documentation
Stream.takeWhile() ↗ Stream.dropWhile() ↗
Proof
View proof source ↗
Related patterns
Streams Beginner

Stream.toList()

Java 8
List<String> result = stream
    .filter(s -> s.length() > 3)
    .collect(Collectors.toList());
Java 16+
List<String> result = stream
    .filter(s -> s.length() > 3)
    .toList();
Hover to see modern ➜
JDK 16+ →
Streams Intermediate

Stream.mapMulti()

Java 8
stream.flatMap(order ->
    order.items().stream()
        .map(item -> new OrderItem(
            order.id(), item)
        )
);
Java 16+
stream.<OrderItem>mapMulti(
    (order, downstream) -> {
        for (var item : order.items())
            downstream.accept(
                new OrderItem(order.id(), item));
    }
);
Hover to see modern ➜
JDK 16+ →
Streams Intermediate

Optional.or() fallback

Java 8
Optional<Config> cfg = primary();
if (!cfg.isPresent()) {
    cfg = secondary();
}
if (!cfg.isPresent()) {
    cfg = defaults();
}
Java 9+
Optional<Config> cfg = primary()
    .or(this::secondary)
    .or(this::defaults);
Hover to see modern ➜
JDK 9+ →
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.