Course contentsShow
← Java
Lesson 1516 of 2,87033. Streams API: Terminal OperationsFree lesson

Collectors.toList() and Mutable vs Immutable Results

Collecting stream elements into a List, understanding that the returned list type is implementation-dependent and mutable.

Collectors.toList() and Mutable vs Immutable Results

What you'll learn: How Collectors.toList() collects stream elements into a List and why the mutability of that list isn't guaranteed.

Understanding Collectors.toList()

When you call stream.collect(Collectors.toList()), the Stream API gathers all elements from your stream and packages them into a List. This is one of the most common terminal operations you'll use.

Here's the crucial part: the Java specification doesn't promise what specific type of List you'll get back. It could be an ArrayList, a custom implementation, or even an immutable list. The only guarantee is that it will be some List.

The Mutability Question

In earlier Java versions, Collectors.toList() typically returned a mutable ArrayList, so code like this worked fine:

List<String> names = Stream.of("Alice", "Bob", "Charlie")
    .collect(Collectors.toList());
names.add("David");  // This usually worked... but wasn't guaranteed!

However, the returned list's mutability is implementation-dependent. The specification allows the JDK to return an immutable list if it chooses. Some JVM implementations or future Java versions might optimize by returning immutable lists, which would cause add(), remove(), or set() operations to throw UnsupportedOperationException.

Think of It Like a Mystery Box

Imagine ordering a "container" online. You know it'll hold your items, but you don't know if it's a plastic bin you can modify or a sealed glass case. That's Collectors.toList() — it holds your data, but don't assume you can change it afterward.

Key Takeaway: Collectors.toList() returns a List, but its concrete type and mutability are not guaranteed by the specification. If you need a specific mutable list, collect to ArrayList explicitly or use other collectors designed for mutability control.