Collections Beginner

Convert streams to typed arrays with a method reference.

โœ• 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);
See a problem with this code? Let us know.
๐ŸŽฏ

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
Typed stream toArray
Available

Widely available since JDK 8 (March 2014)

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.

Share ๐• ๐Ÿฆ‹ in โฌก