toArray and Back Again
Get a real array out of a stream, keep the element type, and stream an array back in.
Open this lesson in the learning hubKey points
toArray()with no argument gives anObject[]. Casting that to a typed array throws ClassCastException at runtime.toArray(String[]::new)passes an array factory, so you get a realString[]back.- Primitive streams already know their type:
mapToInt(...).toArray()hands you anint[]with no boxing. - Going the other way,
Arrays.stream(arr)streams the whole array andArrays.stream(arr, from, to)streams a slice. - A nested array flattens with
flatMap, orflatMapToIntwhen the inner arrays are primitives.
Example
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> names = List.of("ada", "grace", "alan");
Object[] loose = names.stream().toArray();
String[] typed = names.stream().toArray(String[]::new);
int[] lengths = names.stream().mapToInt(String::length).toArray();
System.out.println("loose : Object[" + loose.length + "]");
System.out.println("typed : " + Arrays.toString(typed));
System.out.println("lengths : " + Arrays.toString(lengths));
// Arrays go back the other way too.
System.out.println("back : " + Arrays.stream(typed).map(String::toUpperCase).toList());
System.out.println("slice : " + Arrays.stream(typed, 1, 3).toList());
// A nested array flattens with flatMapToInt.
int[][] grid = {{1, 2}, {3, 4}};
System.out.println("grid sum: " + Arrays.stream(grid).flatMapToInt(Arrays::stream).sum());
// toArray() alone gives Object[], so a cast to String[] blows up at runtime.
try {
String[] bad = (String[]) names.stream().toArray();
System.out.println(bad.length);
} catch (ClassCastException e) {
System.out.println("cast : Object[] is not a String[]");
}
}
}
Always pass the array constructor reference unless Object[] is genuinely what you want.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Streams course, and every lesson in it is listed on the Streams contents page.