Unmodifiable collectors
Collect directly to an unmodifiable list with stream.toList().
Porównanie kodu
✕ Java 8
List<String> list = stream.collect(
Collectors.collectingAndThen(
Collectors.toList(),
Collections::unmodifiableList
)
);
✓ Java 16+
List<String> list = stream.toList();
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
Shortest yet
stream.toList() needs no collect() or Collectors import at all.
Immutable
Result cannot be modified — no accidental mutations.
Readable
Reads naturally as the terminal step of any stream pipeline.
Stare podejście
collectingAndThen
Nowoczesne podejście
stream.toList()
Od JDK
16
Poziom trudności
Średniozaawansowany
Wsparcie JDK
Unmodifiable collectors
Dostępne
Widely available since JDK 16 (March 2021)
Jak to działa
Java 10 added toUnmodifiableList(), toUnmodifiableSet(), and toUnmodifiableMap() to replace the verbose collectingAndThen wrapper. For lists specifically, Java 16's stream.toList() provides an even simpler alternative — no collect() call at all. Use toUnmodifiableSet() and toUnmodifiableMap() for other collection types.
Powiązana dokumentacja