Java Stream dropWhile() Method
dropWhile() is a stateful intermediate operation added to java.util.stream.Stream in Java 9. On an ordered stream, it discards the leading elements that match a Predicate and returns everything from the first element that fails the test onwards, including that element.
It is the mirror image of takeWhile(). Use it to skip a header, warm-up period or leading noise whose length you do not know in advance. This tutorial covers the signature, behaviour on ordered and unordered streams, and the difference from skip() and filter().
1. Syntax and Method Signature
// java.util.stream.Stream<T> (Java 9)
default Stream<T> dropWhile(Predicate<? super T> predicate)
// primitive versions (Java 9)
IntStream IntStream.dropWhile(IntPredicate predicate)
While the predicate returns true, elements are dropped. From the first false onwards, every element is passed on, and the predicate is no longer called.
List<String> afterBlankLines = lines.stream()
.dropWhile(String::isBlank)
.toList();
2. How dropWhile() Works
dropWhile() has two phases. In the dropping phase it tests each element and discards it while the predicate is true. The first element that fails switches it to the passing phase: that element and all later ones are passed on without testing. It is stateful because it remembers which phase it is in.
Unlike takeWhile(), it is not short-circuiting: it always needs the rest of the stream. On ordered streams the result is well defined. On unordered streams where some but not all elements match, the documentation allows any subset of the matching elements to be dropped, so results are nondeterministic.
dropWhile() stops testing and keeps every remaining element, even ones that would match.3. Java Examples
Example 1: Skipping leading debug lines (Java 9+)
A startup log begins with an unknown number of DEBUG lines. Keep everything from the first non-DEBUG line.
import java.util.List;
import java.util.stream.Collectors;
public class DropLeadingDebug {
public static void main(String[] args) {
List<String> log = List.of(
"DEBUG init", "DEBUG config", "INFO ready", "DEBUG cache", "WARN slow");
List<String> fromReady = log.stream()
.dropWhile(line -> line.startsWith("DEBUG"))
.collect(Collectors.toList());
System.out.println(fromReady);
}
}
[INFO ready, DEBUG cache, WARN slow]
How it works: The two leading DEBUG lines are dropped. DEBUG cache is kept because the predicate is no longer checked after the first failure.
Example 2: Trimming leading zeros (Java 9+)
A meter sends readings with zeros until the device warms up. Keep the readings from the first non-zero value.
import java.util.Arrays;
import java.util.stream.IntStream;
public class TrimLeadingZeros {
public static void main(String[] args) {
int[] readings = {0, 0, 0, 7, 0, 9, 12};
int[] meaningful = IntStream.of(readings)
.dropWhile(r -> r == 0)
.toArray();
System.out.println(Arrays.toString(meaningful));
}
}
[7, 0, 9, 12]
How it works: IntStream.dropWhile() removes only the leading zeros. The zero between 7 and 9 is a real reading and stays.
Example 3: Events after a point in time (Java 16+)
Given transactions sorted by time, keep those from 10:00 onwards.
import java.time.LocalTime;
import java.util.List;
public class TransactionsFromTen {
record Txn(LocalTime at, int amount) { }
public static void main(String[] args) {
List<Txn> txns = List.of(
new Txn(LocalTime.of(9, 12), 400),
new Txn(LocalTime.of(9, 47), 1250),
new Txn(LocalTime.of(10, 0), 300),
new Txn(LocalTime.of(11, 30), 880));
LocalTime cutOff = LocalTime.of(10, 0);
int lateTotal = txns.stream()
.dropWhile(t -> t.at().isBefore(cutOff))
.mapToInt(Txn::amount)
.sum();
System.out.println("Total from 10:00: " + lateTotal);
}
}
Total from 10:00: 1180
How it works: Because the list is sorted by time, dropping while the time is before 10:00 removes exactly the early transactions.
Example 4: Combining dropWhile() and takeWhile() (Java 16+)
Extract the body of a document between a BEGIN and an END marker.
import java.util.List;
public class ExtractBody {
public static void main(String[] args) {
List<String> document = List.of(
"header: v2", "author: ops", "BEGIN", "line one", "line two", "END", "footer");
List<String> body = document.stream()
.dropWhile(line -> !line.equals("BEGIN"))
.skip(1) // drop the BEGIN marker itself
.takeWhile(line -> !line.equals("END"))
.toList();
System.out.println(body);
}
}
[line one, line two]
How it works: dropWhile() removes everything up to the BEGIN line, skip(1) removes the marker, and takeWhile() stops at END. Together they slice a section whose position is not known in advance.
4. Real-World Use Cases
- Files and logs: skip preambles, comments or headers of unknown length.
- Time series: start analysis from the first value above a threshold or after a timestamp.
- Sensor data: ignore leading zeros or warm-up noise.
- Sections of text: combined with
takeWhile(), extract the lines between markers.
5. Important Points
- Java 9 or later is required.
- Only leading elements are dropped; later matches are kept.
- All match: if every element matches, the result is empty.
- None match: if the first element fails, the whole stream is returned.
- Ordered streams give deterministic results; unordered ones do not.
- Not short-circuiting: on an infinite stream it needs a later
limit()ortakeWhile().
6. dropWhile() vs Related Methods
| Method | Removes | Since |
|---|---|---|
dropWhile(p) | Leading elements while p is true | Java 9 |
skip(n) | A fixed number of leading elements | Java 8 |
filter(p.negate()) | Every element that matches, anywhere | Java 8 |
takeWhile(p) | Everything from the first failure | Java 9 |
dropWhile() and takeWhile() split an ordered stream at the same point: one returns the part before it, the other the part from it.
7. Common Mistakes and Best Practices
Expecting dropWhile() to remove every match
import java.util.List;
public class DropWhileVsFilter {
public static void main(String[] args) {
List<String> words = List.of("", "", "alpha", "", "beta");
System.out.println("dropWhile: " + words.stream().dropWhile(String::isEmpty).toList());
System.out.println("filter: " + words.stream().filter(w -> !w.isEmpty()).toList());
}
}
dropWhile: [alpha, , beta] filter: [alpha, beta]
dropWhile() removes only the leading empty strings. Use filter() to remove them everywhere.
Other mistakes to avoid
- Using it on unsorted data when the cut-off depends on order; sort first.
- Using it on a
HashSet. The result is nondeterministic. - Forgetting that the boundary element is kept. Add
skip(1)if the marker itself should go, as in Example 4.
8. Summary
dropWhile()(Java 9) drops leading elements while a predicate holds and keeps the rest.- After the first failure, the predicate is no longer tested; later matches are kept.
- It is stateful but not short-circuiting, and deterministic only on ordered streams.
- Combine it with
takeWhile()to extract a section between two markers.
9. References
Frequently Asked Questions (FAQ)
Q1. What does dropWhile() do in Java?
dropWhile(), added in Java 9, discards the leading elements of an ordered stream while a predicate is true and returns all elements from the first one that fails the test, including that element.
Q2. What is the difference between dropWhile() and filter()?
filter() removes every matching element anywhere in the stream. dropWhile() removes only the matching elements at the start and keeps everything after the first non-match, even later matches.
Q3. What is the difference between dropWhile() and skip()?
skip(n) removes a fixed number of elements. dropWhile() removes a variable number of leading elements, decided by a predicate.
Q4. Is dropWhile() short-circuiting?
No. It must pass on every element after the dropping phase, so it reads the whole stream. takeWhile() is the short-circuiting counterpart.
Q5. What happens if all elements match the predicate?
All elements are dropped and the result is an empty stream. If the first element does not match, nothing is dropped.