Typed stream toArray
Convert streams to typed arrays with a method reference.
Code Comparison
✕ 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);
Why the modern way wins
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.
Old Approach
Manual Array Copy
Modern Approach
toArray(generator)
Since JDK
8
Difficulty
beginner
JDK Support
Typed stream toArray
Available
Widely available since JDK 8 (March 2014)
How it works
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.