takeWhile and dropWhile
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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()); }}Loop: [24, 27, 31, 34] takeWhile: [24, 27, 31, 34] Safe hours: 4
What this code does
takeWhileis the loop withbreak: 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
takeWhilenever sees them. - Why: both stop at the first failure, so the cost is the same.
takeWhilenames the intent that abreakonly 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
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); }}Asha,78 Ravi,91 # end of section A Meena,66
What this code does
dropWhiledrops the two comment lines at the top. AtAsha,78the test fails, and from then on every line is kept.- The comment
# end of section Ais kept too, becausedropWhilestops checking after the first failure. Dropping every comment line is a job forfilter.
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.
Example 3 · filter, takeWhile and dropWhile side by side
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()); }}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
filterkeeps every reading below 35, including the 31 after 36.takeWhilestops at 36.dropWhilestarts keeping at 36 and keeps 31 as well.- On sorted data
filterandtakeWhileagree, buttakeWhilestops reading at 40 whilefilterchecks 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,
filterandtakeWhilegive the same result, buttakeWhilestops 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
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)); }}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
ERRORline:takeWhilegives the three lines before it,dropWhilegives that line and everything after. - The
INFOline at 09:07 appears in the second part, becausedropWhilestops 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
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()); }}takeWhile on unsorted: [200, 450] filter: [200, 450, 300, 150] sorted, then takeWhile: [150, 200, 300, 450]
What this code does
- On unsorted data
takeWhilestops at 900 and silently misses 300 and 150. Nothing fails; the list is just incomplete. - Use
filterto get every match in the original order, or sort first so the matches are at the front, and thentakeWhileis 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 2takeWhile, ask: is the data ordered by the thing I am testing? If not, you want filter.Next step
Check your understanding
12 quick questions