Terminal toList() replaces the verbose collect(Collectors.toList()).
Porównanie kodu
✕ Java 8
List<String> result = stream
.filter(s -> s.length() > 3)
.collect(Collectors.toList());
✓ Java 16+
List<String> result = stream
.filter(s -> s.length() > 3)
.toList();
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
7 chars vs 24
.toList() replaces .collect(Collectors.toList()).
Immutable
The result list cannot be modified.
Fluent
Reads naturally at the end of a pipeline.
Stare podejście
Collectors.toList()
Nowoczesne podejście
.toList()
Od JDK
16
Poziom trudności
Początkujący
Wsparcie JDK
Stream.toList()
Dostępne
Widely available since JDK 16 (March 2021)
Jak to działa
Stream.toList() returns an unmodifiable list. It's equivalent to .collect(Collectors.toUnmodifiableList()) but much shorter. Note: the result is immutable, unlike Collectors.toList().
Powiązana dokumentacja