Collections Średniozaawansowany

Collect directly to an unmodifiable list with stream.toList().

✕ 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ć.
📏

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
Unmodifiable collectors
Dostępne

Widely available since JDK 16 (March 2021)

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.

Udostępnij 𝕏 🦋 in