Typed stream toArray
Convert streams to typed arrays with a method reference.
Porównanie kodu
✕ Pre-Streams
List<String> list = getNames();
String[] arr = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
arr[i] = list.get(i);
}
✓ Java 8+
String[] arr = getNames().stream()
.filter(n -> n.length() > 3)
.toArray(String[]::new);
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
Type-safe
No Object[] cast — the array type is correct.
Chainable
Works at the end of any stream pipeline.
Concise
One expression replaces the manual loop.
Stare podejście
Manual Array Copy
Nowoczesne podejście
toArray(generator)
Od JDK
8
Poziom trudności
Początkujący
Wsparcie JDK
Typed stream toArray
Dostępne
Widely available since JDK 8 (March 2014)
Jak to działa
The toArray(IntFunction) method creates a properly typed array from a stream. The generator (String[]::new) tells the stream what type of array to create.
Powiązana dokumentacja