Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is the difference between Collectors.toList() and Stream.toList() in modern Java? Modern Java में Collectors.toList() और Stream.toList() में क्या अंतर है?

Answer
MethodAvailable sinceReturned list mutability
collect(Collectors.toList())Java 8Typically 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?