Sub topic 17
Newer Additions: takeWhile, dropWhile, Stream.toList, and More
The Stream API first shipped with Java 8. Later Java versions added a few small tools that make common tasks shorter. This chapter covers the ones you will use most often.
takeWhile and dropWhile (Java 9)
A predicate is a test that returns true or false for each element. You have already used predicates with filter.
takeWhilekeeps elements while the predicate istrue. It stops at the first element that fails and ignores everything after it.dropWhiledoes the opposite. It skips elements while the predicate istrue, then keeps the first element that fails and everything after it.
These two are different from filter. A filter checks every element. takeWhile and dropWhile care only about the first element that fails the test.
Stream.toList (Java 16)
Before Java 16, you collected results with .collect(Collectors.toList()). Now you can write .toList(). It returns an unmodifiable list, which means a list you cannot add to, remove from, or change.
import java.util.List;
public class ModernExample {
public static void main(String[] args) {
// Java 9+: takeWhile and dropWhile; Java 16+: Stream.toList
List<Integer> numbers = List.of(1, 2, 3, 10, 4, 5);
List<Integer> prefix = numbers.stream()
.takeWhile(n -> n < 5)
.toList();
List<Integer> rest = numbers.stream()
.dropWhile(n -> n < 5)
.toList();
System.out.println(prefix); // [1, 2, 3]
System.out.println(rest); // [10, 4, 5]
}
}Notice that 4 and 5 are not in prefix, even though they are less than 5. takeWhile stopped at 10.
More Helpers
Java 9 also added these:
| Method | What it does |
|---|---|
| `Stream.iterate(seed, hasNext, next)` | Builds a sequence that stops once `hasNext` returns `false`, so you do not need `limit` |
| `Stream.ofNullable(x)` | Makes a stream with one element, or an empty stream if `x` is `null` |
import java.util.List;
import java.util.stream.Stream;
public class MoreHelpers {
public static void main(String[] args) {
List<Integer> powers = Stream.iterate(1, n -> n < 20, n -> n * 2)
.toList();
System.out.println(powers); // [1, 2, 4, 8, 16]
String missing = null;
System.out.println(Stream.ofNullable(missing).count()); // 0
}
}The three-argument iterate works like a for loop. It takes a start value, a test that decides whether to continue, and a step that produces the next value.
Exercise
Given List.of(2, 4, 6, 7, 8), what do takeWhile(n -> n % 2 == 0) and filter(n -> n % 2 == 0) each return?
Show answer
takeWhile returns [2, 4, 6] because it stops at the first odd number, 7. filter returns [2, 4, 6, 8] because it checks every element.
Exercise
Write a pipeline using the three-argument Stream.iterate that produces [10, 20, 30, 40].
Show answer
Stream.iterate(10, n -> n <= 40, n -> n + 10).toList()