Collections Beginner

Filter a collection and collect the results to a typed array using a single stream expression.

✕ Pre-Streams
List<String> list = getNames();
List<String> filtered = new ArrayList<>();
for (String n : list) {
    if (n.length() > 3) {
        filtered.add(n);
    }
}
String[] arr = filtered.toArray(new String[0]);
✓ 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

No intermediate list — one expression replaces the manual loop and copy.

Old Approach
Manual Filter + Copy
Modern Approach
toArray(generator)
Since JDK
8
Difficulty
Beginner
Typed stream toArray
Available

Widely available since JDK 8 (March 2014)

When you need to filter a collection before converting it to a typed array, streams let you chain the operations without an intermediate list. The toArray(IntFunction) generator (String[]::new) creates the correctly typed array directly at the end of the pipeline, eliminating the manual loop and temporary ArrayList.