Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Streams and Functional

Java Stream takeWhile() and dropWhile()

Reference for Java 9 Stream.takeWhile() and dropWhile(): keep or discard the leading run of elements that match a condition, and how they differ from filter().

takeWhile(predicate) (Java 9) returns the longest leading run of elements that satisfy the predicate and stops at the first one that does not. dropWhile(predicate) is its complement: it discards that leading run and returns everything from the first failing element onward, including later elements that would match again.

Both are about the stream's prefix, which makes them different from filter(): they look at order, and takeWhile can end an infinite stream.

Java
Stream.of(1, 2, 3, 10, 2).takeWhile(n -> n < 5);   // 1, 2, 3
Stream.of(1, 2, 3, 10, 2).dropWhile(n -> n < 5);   // 10, 2

Try it

Java Prefix, remainder and filter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Infinite streams and sorted data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
Stream<T> takeWhile(Predicate<? super T> predicate)
Stream<T> dropWhile(Predicate<? super T> predicate)

Also on IntStream, LongStream and DoubleStream with the matching primitive predicates.

Name Description
predicate Stateless, non-interfering test applied to elements in order.

Returns: the matching prefix (takeWhile) or the stream after it (dropWhile).

Usage notes

  • Ordered streams: on an ordered stream both are deterministic and stop at the first failure. On an unordered stream the result may be any subset that satisfies the contract, which is rarely what you want.
  • Short-circuit: takeWhile stops pulling after the first non-match, so it works on infinite streams. dropWhile does not short-circuit; it must still process the rest.
  • Parallel streams: both are costly in parallel because order has to be maintained. Prefer sequential streams.
  • Versus filter: filter tests every element; these two react only to the first failure. With data like [1, 2, 3, 10, 2, 1] they give different answers.
  • Versus limit: use limit(n) for a count and takeWhile for a condition.
  • Sorted data: takeWhile is a neat way to read "all values up to X" without checking the rest.
  • Stream.iterate(seed, hasNext, next) (Java 9) often replaces an infinite iterate plus takeWhile.