Stream.toList vs Collectors.toList: Which Java List Conversion Is Faster?
This article compares Java's Stream.toList(), Collectors.toList(), and Collectors.toUnmodifiableList() by explaining their differences, showing benchmark code, presenting performance results for both 1,000 and 10,000 element streams, and concluding which method offers superior speed and efficiency.
Previously introduced Java 16 Stream enhancements, including direct toList() conversion.
The common ways to convert a Stream to a List are:
list.stream().toList();
list.stream().collect(Collectors.toList());
list.stream().collect(Collectors.toUnmodifiableList());Readers often ask about the difference between Stream.toList() and Collectors.toList() and their performance. Stream.toList() returns an immutable list. Collectors.toList() returns a mutable list. Collectors.toUnmodifiableList() also returns an immutable list.
We benchmarked the three methods using JMH.
@BenchmarkMode(Mode.All)
@Fork(1)
@State(Scope.Thread)
@Warmup(iterations = 20, time = 1, batchSize = 10000)
@Measurement(iterations = 20, time = 1, batchSize = 10000)
public class BenchmarkStreamToList {
@Benchmark
public List<Integer> streamToList() {
return IntStream.range(1, 1000).boxed().toList();
}
@Benchmark
public List<Integer> collectorsToList() {
return IntStream.range(1, 1000).boxed().collect(Collectors.toList());
}
@Benchmark
public List<Integer> collectorsToUnmodifiableList() {
return IntStream.range(1, 1000).boxed().collect(Collectors.toUnmodifiableList());
}
}The benchmark results show that streamToList outperforms both collector variants in throughput, average latency, and tail‑latency metrics, even when the element count is increased to 10,000.
Conclusion: Stream.toList() provides better overall performance compared to Collectors.toList() and Collectors.toUnmodifiableList().
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
