Interview question
What is the difference between Collectors.toList() and Stream.toList() in modern Java? Modern Java में Collectors.toList() और Stream.toList() में क्या अंतर है?
Answer
| Method | Available since | Returned list mutability |
|---|---|---|
| collect(Collectors.toList()) | Java 8 | Typically mutable (ArrayList), but not officially guaranteed |
| .toList() | Java 16+ | Unmodifiable - guaranteed immutable |
import java.util.stream.*;
List<String> names = List.of('Charlie', 'Alice', 'Bob');
// Java 8 style - via Collectors
List<String> result1 = names.stream()
.filter(n -> n.length() > 3)
.collect(Collectors.toList());
result1.add('Extra'); // usually works - typically returns a mutable ArrayList
// Java 16+ shorthand - more concise
List<String> result2 = names.stream()
.filter(n -> n.length() > 3)
.toList();
// result2.add('Extra'); // UnsupportedOperationException - immutable by design
// Also useful in modern Java: Collectors.toUnmodifiableList() (Java 10+)
// gives the SAME guarantee as .toList() but with more explicit intent
List<String> result3 = names.stream()
.collect(Collectors.toUnmodifiableList());
// Practical implication: if you build a list with .toList() and later
// need to modify it, wrap it explicitly:
List<String> mutableCopy = new ArrayList<>(result2);
mutableCopy.add('Extra'); // now works
// Choose .toList() for concise, safe-by-default code in Java 16+ projects;
// use Collectors.toList() when you specifically need a mutable result
// or need to target compatibility with Java 8-15| Method | कब से उपलब्ध | Mutability |
|---|---|---|
| collect(Collectors.toList()) | Java 8 | आमतौर पर mutable |
| .toList() | Java 16+ | Unmodifiable |
import java.util.stream.*;
List<String> names = List.of('Charlie', 'Alice', 'Bob');
// Java 8 style
List<String> result1 = names.stream()
.filter(n -> n.length() > 3)
.collect(Collectors.toList());
result1.add('Extra'); // आमतौर पर काम करता है
// Java 16+ shorthand
List<String> result2 = names.stream()
.filter(n -> n.length() > 3)
.toList();
// result2.add('Extra'); // UnsupportedOperationException
List<String> result3 = names.stream()
.collect(Collectors.toUnmodifiableList());
List<String> mutableCopy = new ArrayList<>(result2);
mutableCopy.add('Extra'); // अब काम करता हैWas this answer clear?