Skip to lesson

takeWhile and dropWhile

takeWhile keeps elements from the start of a stream as long as a condition holds and stops at the first one that fails. dropWhile does the opposite: it throws elements away while the condition holds and passes on everything from the first failure onwards. Both arrived in Java 9.

takeWhile: keep the front, stop at the first failure

takeWhile (Java 9) keeps the longest front part of the stream where the test is true. At the first element that fails, it ends the stream, even if later elements would pass.

Think of a loop with break: walk the list, and the moment a value fails the test, leave the loop. takeWhile(predicate) is exactly that.

Example 1 · takeWhile versus a loop with break

TakeWhileDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class TakeWhileDemo {    public static void main(String[] args) {        // temperature every hour from 6 am        List<Integer> temps = List.of(24, 27, 31, 34, 36, 33, 29);
        List<Integer> loopResult = new ArrayList<>();        for (int t : temps) {            if (t >= 35) {                break;            }            loopResult.add(t);        }        System.out.println("Loop:      " + loopResult);
        List<Integer> beforeHeat = temps.stream()                .takeWhile(t -> t < 35)                .toList();        System.out.println("takeWhile: " + beforeHeat);        System.out.println("Safe hours: " + beforeHeat.size());    }}
Output
Loop:      [24, 27, 31, 34]
takeWhile: [24, 27, 31, 34]
Safe hours: 4

What this code does

  • takeWhile is the loop with break: it keeps 24, 27, 31, 34 and stops at 36.
  • 33 and 29 are below 35 too, but they come after the first failure, so takeWhile never sees them.
  • Why: both stop at the first failure, so the cost is the same. takeWhile names the intent that a break only implies.

Like limit, it is short-circuiting: once it stops, nothing more is read from the source. That makes it useful on long or sorted data, where you know the interesting part sits at the front.

dropWhile: skip the front, keep the rest

dropWhile (Java 9) drops the front part of the stream where the test is true and keeps everything from the first failing element on, even if later elements would fail.

dropWhile(predicate) throws elements away while the predicate is true. At the first false it stops checking, and that element and everything after it are passed on, even later elements that would have matched the predicate.

Example 2 · dropWhile skips a header

DropWhileDemo.javaJava
import java.util.List;
public class DropWhileDemo {    public static void main(String[] args) {        List<String> file = List.of(                "# marks.csv",                "# exported from the college portal",                "Asha,78",                "Ravi,91",                "# end of section A",                "Meena,66");
        List<String> data = file.stream()                .dropWhile(line -> line.startsWith("#"))                .toList();        data.forEach(System.out::println);    }}
Output
Asha,78
Ravi,91
# end of section A
Meena,66

What this code does

  • dropWhile drops the two comment lines at the top. At Asha,78 the test fails, and from then on every line is kept.
  • The comment # end of section A is kept too, because dropWhile stops checking after the first failure. Dropping every comment line is a job for filter.

Typical uses are skipping a header: comment lines at the top of a file, a warm-up period at the start of sensor readings, or all log lines before the first error. takeWhile and dropWhile with the same predicate split a stream at the same point: takeWhile gives the front part, dropWhile gives the back part, and together they hold every element exactly once.

How they differ from filter

filter tests every element and keeps each one that passes, wherever it is. takeWhile and dropWhile care only about where the condition first fails; after that point they stop testing.

Take the readings 30, 32, 36, 31, 38 and the test t < 35.

Readings 30, 32, 36, 31, 38 with the test t < 35. filter keeps every passing reading: 30, 32, 31. takeWhile stops at the first failure, 36: 30, 32. dropWhile drops the passing front and keeps the rest: 36, 31, 38.

Example 3 · filter, takeWhile and dropWhile side by side

SideBySideDemo.javaJava
import java.util.List;
public class SideBySideDemo {    public static void main(String[] args) {        List<Integer> readings = List.of(30, 32, 36, 31, 38);
        System.out.println("filter(t < 35):    " + readings.stream().filter(t -> t < 35).toList());        System.out.println("takeWhile(t < 35): " + readings.stream().takeWhile(t -> t < 35).toList());        System.out.println("dropWhile(t < 35): " + readings.stream().dropWhile(t -> t < 35).toList());
        List<Integer> sorted = List.of(10, 20, 30, 40, 50);        System.out.println("Sorted, filter:    " + sorted.stream().filter(n -> n < 35).toList());        System.out.println("Sorted, takeWhile: " + sorted.stream().takeWhile(n -> n < 35).toList());    }}
Output
filter(t < 35):    [30, 32, 31]
takeWhile(t < 35): [30, 32]
dropWhile(t < 35): [36, 31, 38]
Sorted, filter:    [10, 20, 30]
Sorted, takeWhile: [10, 20, 30]

What this code does

  • filter keeps every reading below 35, including the 31 after 36. takeWhile stops at 36. dropWhile starts keeping at 36 and keeps 31 as well.
  • On sorted data filter and takeWhile agree, but takeWhile stops reading at 40 while filter checks all five.

On those readings:

  • filter(t -> t < 35) gives [30, 32, 31]: every reading below 35, including the 31 after the hot spell.
  • takeWhile(t -> t < 35) gives [30, 32]: it stops at 36 and never looks at 31.
  • dropWhile(t -> t < 35) gives [36, 31, 38]: it drops until 36, then keeps everything, including 31.
  • On data sorted by the same key, filter and takeWhile give the same result, but takeWhile stops reading early.

Real-world use: log lines until the first error

A server log is in time order. Support wants to know what happened before the first error, to see what led up to it. That is takeWhile(line -> !line.startsWith("ERROR")). They also want the error and everything after it, which is dropWhile with the same predicate.

Example 4 · Real-world use: the log before and after the first error

LogDemo.javaJava
import java.util.List;import java.util.function.Predicate;
public class LogDemo {    public static void main(String[] args) {        List<String> log = List.of(                "INFO  09:00 server started",                "INFO  09:02 user asha logged in",                "WARN  09:05 slow response from payment gateway",                "ERROR 09:06 payment timeout for order 5512",                "INFO  09:07 retrying order 5512",                "ERROR 09:08 payment failed for order 5512");
        Predicate<String> notError = line -> !line.startsWith("ERROR");
        System.out.println("Lead-up to the first error:");        log.stream()                .takeWhile(notError)                .forEach(line -> System.out.println("  " + line));
        System.out.println("From the first error on:");        log.stream()                .dropWhile(notError)                .forEach(line -> System.out.println("  " + line));    }}
Output
Lead-up to the first error:
  INFO  09:00 server started
  INFO  09:02 user asha logged in
  WARN  09:05 slow response from payment gateway
From the first error on:
  ERROR 09:06 payment timeout for order 5512
  INFO  09:07 retrying order 5512
  ERROR 09:08 payment failed for order 5512

What this code does

  • The same predicate splits the log at the first ERROR line: takeWhile gives the three lines before it, dropWhile gives that line and everything after.
  • The INFO line at 09:07 appears in the second part, because dropWhile stops testing after the first failure.

Both work only because a log is in time order: "before the first error" has a meaning. The same logic suits a bank statement sorted by date (transactions until the balance first goes negative) or a sorted price list (items you can afford, cheapest first).

Trap: takeWhile and dropWhile on unsorted data

Both methods assume the elements you want sit together at the front. On unsorted data that is usually false: takeWhile(p -> p <= 500) on prices 200, 450, 900, 300, 150 stops at 900 and silently misses 300 and 150.

Example 5 · Trap: takeWhile on unsorted prices

UnsortedTrapDemo.javaJava
import java.util.List;
public class UnsortedTrapDemo {    public static void main(String[] args) {        List<Integer> prices = List.of(200, 450, 900, 300, 150);        int budget = 500;
        System.out.println("takeWhile on unsorted: " + prices.stream()                .takeWhile(p -> p <= budget).toList());        System.out.println("filter:                " + prices.stream()                .filter(p -> p <= budget).toList());        System.out.println("sorted, then takeWhile: " + prices.stream()                .sorted()                .takeWhile(p -> p <= budget).toList());    }}
Output
takeWhile on unsorted: [200, 450]
filter:                [200, 450, 300, 150]
sorted, then takeWhile: [150, 200, 300, 450]

What this code does

  • On unsorted data takeWhile stops at 900 and silently misses 300 and 150. Nothing fails; the list is just incomplete.
  • Use filter to get every match in the original order, or sort first so the matches are at the front, and then takeWhile is both correct and quick.

If you mean "all items matching the rule", use filter. If you mean "the front part", sort by the same key first, so the matching elements really are at the front. On a source with no fixed order, such as a HashSet, the result can even change from run to run, so do not use them there at all.

Find the bug

Find the front-only mistake

Tap the line that is wrong, then check the fix.

Keep every price up to 500.

Round 1 of 2
Before writing takeWhile, ask: is the data ordered by the thing I am testing? If not, you want filter.

Next step

Check your understanding

12 quick questions