toList() versus collect(Collectors.toList())
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A stream gives you its results as a list in three ways: toList(), collect(Collectors.toList()) and collect(Collectors.toUnmodifiableList()). They hold the same elements, but they differ in one thing that causes real bugs: whether you can change the list afterwards.
Stream.toList() returns an unmodifiable list
Stream.toList() was added in Java 16. It is the shortest way to end a pipeline: List<String> names = students.stream().map(Student::name).toList();.
List<String> names = Stream.of("Asha", "Ravi").toList();System.out.println(names); // [Asha, Ravi]names.add("Meena"); // UnsupportedOperationException at run timeThe list it returns is unmodifiable: you cannot add, remove, replace or sort its elements. Any attempt throws UnsupportedOperationException at run time; the compiler does not warn you, because the type is still plain List.
This is usually what you want. A result list that nobody can change by mistake is safe to pass around and safe to share between threads. It does allow null elements, unlike List.of.
Collectors.toList() and Collectors.toUnmodifiableList()
Before Java 16, the standard way was collect(Collectors.toList()). A collector is a recipe that tells collect how to build a result; Collectors is a class full of ready-made ones. The Stream Collectors module covers many more.
Example 1 · Three ways to get a list
import java.util.List;import java.util.stream.Collectors;
record Student(String name, int marks) {}
public class ThreeListsDemo { public static void main(String[] args) { List<Student> students = List.of( new Student("Aarav", 78), new Student("Priya", 38), new Student("Rohan", 85));
List<String> a = students.stream() .filter(s -> s.marks() >= 40) .map(Student::name) .toList(); List<String> b = students.stream() .filter(s -> s.marks() >= 40) .map(Student::name) .collect(Collectors.toList()); List<String> c = students.stream() .filter(s -> s.marks() >= 40) .map(Student::name) .collect(Collectors.toUnmodifiableList());
System.out.println("toList(): " + a); System.out.println("Collectors.toList(): " + b); System.out.println("toUnmodifiableList(): " + c); System.out.println("Same elements? " + (a.equals(b) && b.equals(c)));
b.add("Kavya"); // works: Collectors.toList() gave an ArrayList System.out.println("After add to b: " + b); }}toList(): [Aarav, Rohan] Collectors.toList(): [Aarav, Rohan] toUnmodifiableList(): [Aarav, Rohan] Same elements? true After add to b: [Aarav, Rohan, Kavya]
What this code does
- All three lists hold the same names in the same order, and
equalscompares only the elements. The difference is hidden until someone tries to change one. b.add("Kavya")works becauseCollectors.toList()returns anArrayListtoday. Callingaddonaorcwould throw.
Collectors.toList() makes no promise about the list type or whether it can change. Today it returns an ArrayList, so add works, and much old code depends on that. If you need a list you can change, say so clearly: collect(Collectors.toCollection(ArrayList::new)) or new ArrayList<>(stream.toList()). Collectors.toUnmodifiableList() (Java 10) returns an unmodifiable list, like toList(). One difference: it throws a NullPointerException if any element is null, while toList() accepts nulls.
toList(): unmodifiable, allowsnull, Java 16+, shortest.collect(Collectors.toList()): modifiable in practice (anArrayList), not promised.collect(Collectors.toUnmodifiableList()): unmodifiable, rejectsnull, Java 10+.- Need to change it later:
collect(Collectors.toCollection(ArrayList::new)).
Trap: UnsupportedOperationException when adding
A common upgrade bug: old code wrote collect(Collectors.toList()) and later added items to the result. Someone "cleans it up" to toList(), it compiles fine, and the program crashes the first time it reaches add.
Example 2 · Trap: adding to the result of toList()
import java.util.List;
public class ToListTrapDemo { public static void main(String[] args) { List<Integer> marks = List.of(72, 38, 91, 64);
List<Integer> passed = marks.stream() .filter(m -> m >= 40) .toList(); System.out.println("Passed: " + passed);
passed.add(55); // a re-evaluated student also passed System.out.println("After update: " + passed); }}Passed: [72, 91, 64] Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142) at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.add(ImmutableCollections.java:147) at ToListTrapDemo.main(ToListTrapDemo.java:12)
What this code does
- The code compiles, because
passedis a plainListandListhas anaddmethod. The list itself refuses the change at run time and throwsUnsupportedOperationException. - The stack trace points at line 12, the
add. Fix: collect into a list you own,new ArrayList<>(marks.stream().filter(m -> m >= 40).toList()), or build the updated list with another stream.
Example 3 · Which lists can change? Checking each one
import java.util.ArrayList;import java.util.List;import java.util.stream.Collectors;
public class ChangeCheckDemo { static void tryAdd(String label, List<String> list) { try { list.add("Kavya"); System.out.println(label + " add worked: " + list); } catch (UnsupportedOperationException e) { System.out.println(label + " add failed: UnsupportedOperationException"); } }
public static void main(String[] args) { List<String> names = List.of("Rohan", "Aarav");
tryAdd("toList() ", names.stream().toList()); tryAdd("toUnmodifiableList ", names.stream().collect(Collectors.toUnmodifiableList())); tryAdd("Collectors.toList()", names.stream().collect(Collectors.toList())); tryAdd("toCollection ", names.stream().collect(Collectors.toCollection(ArrayList::new))); tryAdd("new ArrayList copy ", new ArrayList<>(names.stream().toList()));
List<String> sortedCopy = new ArrayList<>(names.stream().toList()); sortedCopy.sort(null); System.out.println("Sorted copy: " + sortedCopy); }}toList() add failed: UnsupportedOperationException toUnmodifiableList add failed: UnsupportedOperationException Collectors.toList() add worked: [Rohan, Aarav, Kavya] toCollection add worked: [Rohan, Aarav, Kavya] new ArrayList copy add worked: [Rohan, Aarav, Kavya] Sorted copy: [Aarav, Rohan]
What this code does
toList()andtoUnmodifiableList()refuse every change.Collectors.toList()happens to allow it, but the documentation does not promise that.- When you need a list you will change, ask for one clearly:
Collectors.toCollection(ArrayList::new)or anew ArrayList<>(...)copy. Then sorting and adding are always safe.
Example 4 · Nulls: toList() accepts them, toUnmodifiableList() does not
import java.util.Arrays;import java.util.List;import java.util.Objects;import java.util.stream.Collectors;
public class NullsInListDemo { public static void main(String[] args) { // phone numbers from a form; one student left it blank List<String> phones = Arrays.asList("98450 11111", null, "99000 22222");
List<String> a = phones.stream().toList(); System.out.println("toList(): " + a);
try { List<String> b = phones.stream().collect(Collectors.toUnmodifiableList()); System.out.println("toUnmodifiableList(): " + b); } catch (NullPointerException e) { System.out.println("toUnmodifiableList(): NullPointerException"); }
List<String> clean = phones.stream().filter(Objects::nonNull).toList(); System.out.println("Without nulls: " + clean); }}toList(): [98450 11111, null, 99000 22222] toUnmodifiableList(): NullPointerException Without nulls: [98450 11111, 99000 22222]
What this code does
Arrays.asListallowsnull, so the list holds a blank entry.toList()keeps it;Collectors.toUnmodifiableList()throws as soon as it meets thenull.- Usually the best fix is to remove nulls before collecting:
filter(Objects::nonNull). Then all three ways give the same clean list.
The same happens with remove, set, clear and sort on the result. Before you swap one for the other, search for code that changes the list later. The fix is to decide what the list is for. If it is a finished result, keep toList() and build a new list when something changes. If the code must keep editing it, collect into an ArrayList on purpose.
toArray(String[]::new) for arrays
Some older APIs want an array. toArray() with no argument returns an Object[], which you cannot use as a String[] without copying.
Example 5 · toArray(String[]::new) and int arrays
import java.util.Arrays;import java.util.List;
public class ToArrayDemo { public static void main(String[] args) { List<String> cities = List.of("pune", "delhi", "goa");
Object[] objects = cities.stream().map(String::toUpperCase).toArray(); String[] names = cities.stream().map(String::toUpperCase).toArray(String[]::new); int[] lengths = cities.stream().mapToInt(String::length).toArray();
System.out.println("Object[]: " + Arrays.toString(objects)); System.out.println("String[]: " + Arrays.toString(names)); System.out.println("int[]: " + Arrays.toString(lengths)); System.out.println("First city has " + names[0].length() + " letters"); }}Object[]: [PUNE, DELHI, GOA] String[]: [PUNE, DELHI, GOA] int[]: [4, 5, 3] First city has 4 letters
What this code does
toArray()returnsObject[], soobjects[0].length()would not compile.toArray(String[]::new)passes a generator that makes aString[]of the right size, so the elements are typed.mapToInt(...).toArray()gives a plainint[].Arrays.toStringprints the elements; printing the array itself would show something like[I@1b6d3586.
toArray(String[]::new) takes a generator: a function that creates an array of the right type and size. String[]::new is a constructor reference for size -> new String[size]. The result is a real String[]. For numbers, mapToInt(...).toArray() gives an int[] with no boxing. Print arrays with Arrays.toString(arr), because printing an array directly shows only its type and hash code.
Next step
Check your understanding
11 quick questions