Sub topic 17
Newer Additions: takeWhile, dropWhile, Stream.toList, and More
The Stream API arrived in Java 8. Later versions of Java added more tools to it. This chapter covers the additions you are most likely to use. Each one replaces a longer piece of code you would otherwise write yourself.
Some features need a newer JDK. A JDK (Java Development Kit) is the toolset you use to compile and run Java. If you are on Java 8, the code in this chapter will not compile. Check your version with java -version.
A Quick Map of What Was Added
The table lists each addition and the Java version that brought it.
| Addition | Java version | What it does |
|---|---|---|
| `takeWhile` | 9 | Keeps elements until one fails a test, then stops |
| `dropWhile` | 9 | Skips elements until one fails a test, then keeps the rest |
| `Stream.iterate` with three arguments | 9 | Builds a sequence that stops on its own |
| `Stream.ofNullable` | 9 | Makes a stream of zero or one element |
| `Collectors.toUnmodifiableList` | 10 | Collects into a list that cannot be changed |
| `Collectors.teeing` | 12 | Runs two collectors at once and combines their results |
| `Stream.toList` | 16 | A shorter way to collect into a list that cannot be changed |
takeWhile and dropWhile
A predicate is a test that returns true or false for each element. n -> n < 5 is a predicate.
takeWhile keeps elements from the start of the stream as long as the predicate is true. When it reaches the first element that fails the test, it stops. It ignores every element after that point, even ones that would pass.
dropWhile does the opposite. It throws away elements from the start while the predicate is true. Once one element fails the test, it keeps that element and everything after it.
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]
}
}Look at the 4 in the list. It is less than 5, but takeWhile does not keep it. The stream already stopped at 10. For the same reason, dropWhile keeps 4, because it stopped dropping at 10.
How These Differ from filter
filter checks every element and keeps all that pass. filter(n -> n < 5) on the same list gives [1, 2, 3, 4]. takeWhile and dropWhile care about position. They split the stream at one point.
takeWhile is also short-circuiting. That means it can stop early without reading the rest of the stream. This makes it safe to use on an infinite stream, which is a stream that never runs out of elements.
Stream.toList
Before Java 16, you collected into a list with .collect(Collectors.toList()). Java 16 added .toList() directly on the stream. It is shorter and easier to read.
There is one important difference. The list from Stream.toList() is unmodifiable. Unmodifiable means you cannot add, remove, or replace elements. If you try, Java throws an UnsupportedOperationException.
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ToListExample {
public static void main(String[] args) {
List<String> fixed = Stream.of("a", "b").toList();
try {
fixed.add("c");
} catch (UnsupportedOperationException e) {
System.out.println("toList result cannot be changed");
}
List<String> changeable = Stream.of("a", "b")
.collect(Collectors.toCollection(ArrayList::new));
changeable.add("c");
System.out.println(changeable); // [a, b, c]
}
}If you need to change the list later, collect with Collectors.toCollection(ArrayList::new). That always gives you an ArrayList. Collectors.toList() usually returns an ArrayList too, but the Java documentation does not promise it.
The three list options behave differently:
| Method | Can you change the list? | Allows null elements? |
|---|---|---|
| `collect(Collectors.toList())` | Not guaranteed either way | Yes |
| `collect(Collectors.toUnmodifiableList())` | No | No, throws `NullPointerException` |
| `toList()` | No | Yes |
Stream.iterate with a Stop Condition
In Java 8, Stream.iterate(seed, next) makes an infinite stream. The seed is the first value, and next computes each following value. You had to add limit to stop it.
Java 9 added a three-argument version: Stream.iterate(seed, hasNext, next). The middle argument is a predicate. The stream ends as soon as a value fails it. This works like a for loop: start value, condition, update step.
Stream.ofNullable
Sometimes a value might be null, which means "no value". Stream.ofNullable(x) returns an empty stream if x is null. Otherwise it returns a stream with one element. You can skip writing an if check.
import java.util.List;
import java.util.stream.Stream;
public class IterateOfNullableExample {
public static void main(String[] args) {
List<Integer> powers = Stream.iterate(1, n -> n <= 100, n -> n * 2)
.toList();
System.out.println(powers); // [1, 2, 4, 8, 16, 32, 64]
String missing = null;
System.out.println(Stream.ofNullable(missing).count()); // 0
System.out.println(Stream.ofNullable("here").count()); // 1
}
}The value 128 is not in the result. It fails the test n <= 100, so the stream ends before it.
Collectors.teeing
Sometimes you want two results from the same data, such as a count and an average. Collectors.teeing (Java 12) sends each element to two collectors at once. It then passes both results to a function that combines them. You get both results in one pass over the data.
import java.util.List;
import java.util.stream.Collectors;
public class TeeingExample {
public static void main(String[] args) {
List<Integer> scores = List.of(70, 85, 90, 60);
String report = scores.stream()
.collect(Collectors.teeing(
Collectors.counting(),
Collectors.averagingInt(n -> n),
(count, avg) -> count + " scores, average " + avg));
System.out.println(report); // 4 scores, average 76.25
}
}The name comes from a T-shaped pipe fitting, which splits one flow into two.
Exercises
Exercise
What does List.of(2, 4, 6, 7, 8, 10).stream().takeWhile(n -> n % 2 == 0).toList() return, and what would dropWhile with the same predicate return?
Show answer
takeWhile returns [2, 4, 6]. It stops at 7, the first odd number, so 8 and 10 are not kept. dropWhile returns [7, 8, 10]. It drops the even numbers before 7, then keeps 7 and everything after it.
Exercise
A teammate writes List<String> names = stream.toList(); and later calls names.add("Zoe"). What happens, and how should they fix it?
Show answer
The call throws UnsupportedOperationException, because Stream.toList returns an unmodifiable list. If they need to add elements, they should collect with .collect(Collectors.toCollection(ArrayList::new)), or copy the result into a new ArrayList<>(names).
Exercise
Write a single stream expression, without using limit, that produces the list [10, 20, 30, 40, 50].
Show answer
Stream.iterate(10, n -> n <= 50, n -> n + 10).toList(). The three-argument iterate starts at 10, adds 10 each step, and stops when the value passes 50.