takeWhile: Taking Elements While a Condition Holds
You'll learn how to use takeWhile to grab consecutive elements from a stream until the first one fails your condition.
The Core Idea
takeWhile processes elements in order and includes each one in the result as long as your predicate returns true. The moment it encounters an element that fails the test, it stops completely and ignores everything after that—even if later elements would pass.
Think of it like eating candies from a bag: you keep taking them while they're your favorite flavor, but the instant you hit a different flavor, you stop taking any more, even if your favorites appear again deeper in the bag.
How It Works
Stream.of(2, 4, 6, 7, 8, 10)
.takeWhile(n -> n % 2 == 0)
.forEach(System.out::println);
// Output: 2, 4, 6
// Stops at 7 (first odd number), ignoring 8 and 10
The predicate n -> n % 2 == 0 checks if numbers are even. Elements 2, 4, and 6 pass, but 7 fails—so takeWhile stops there.
Key Difference from filter
Unlike filter (which checks every element), takeWhile only examines elements until the first failure. Order matters critically:
Stream.of(1, 3, 2, 4, 6)
.takeWhile(n -> n < 5)
.forEach(System.out::println);
// Output: 1, 3, 2
// Stops at 4 (fails n < 5), doesn't see 6
Why Use takeWhile?
It's perfect for ordered data where you want leading elements matching a condition—sorted lists, time-ordered events, or any sequential data where a boundary condition signals "stop here."
Key Takeaway:
takeWhile selects consecutive leading elements while a predicate holds true, stopping immediately at the first mismatch—making it ideal for processing ordered data up to a boundary condition.