Video in progress
How do takeWhile() and dropWhile() differ from filter()?
filter checks every element. takeWhile takes elements until the condition fails for the first time and then stops; dropWhile discards that part and lets the rest through in full. Both were added in Java 9 and make sense on ordered data.
📖 Answer
List<Integer> nums = List.of(1, 3, 5, 6, 7, 9);
nums.stream().filter(n -> n % 2 == 1).toList(); // [1, 3, 5, 7, 9]
nums.stream().takeWhile(n -> n % 2 == 1).toList(); // [1, 3, 5]
nums.stream().dropWhile(n -> n % 2 == 1).toList(); // [6, 7, 9]
takeWhile stops when it reaches 6 and doesn't even look at 7 and 9.
The practical benefit is with sorted data and infinite streams:
// from logs sorted by date, only today's
List<LogEntry> today = sortedDesc.stream()
.takeWhile(e -> e.time().toLocalDate().equals(LocalDate.now()))
.toList();
// stopping an infinite stream with a condition
Stream.iterate(1, n -> n * 2).takeWhile(n -> n < 1000).forEach(System.out::println);
On an infinite stream, if you write filter(n -> n < 1000) the program never ends: filter doesn't know when to stop.
If you use them with an unordered source (HashSet), the result may differ each time. The documentation calls this "nondeterministic" as well.
Sign up to mark studied questions and save your progress.