flatMap with Arrays: Arrays.stream()
What you'll learn: How to use Arrays.stream() inside flatMap to convert arrays into streams and flatten them into a single stream.
The Core Challenge
When you have a stream of arrays (like Stream<String[]> or Stream<int[]>), you need a way to convert each array into a stream before flattening. That's where Arrays.stream() comes in—it bridges the gap between arrays and the Stream API.
How Arrays.stream() Fits with flatMap
The flatMap operation requires you to return a Stream from its lambda. When your data is in array form, Arrays.stream(array) converts that array into a stream, which flatMap then flattens.
Basic pattern:
streamOfArrays.flatMap(array -> Arrays.stream(array))
Practical Example
String[][] arrayOfArrays = {
{"Java", "Python"},
{"C++", "JavaScript", "Go"},
{"Ruby"}
};
Stream<String> flattened = Arrays.stream(arrayOfArrays)
.flatMap(array -> Arrays.stream(array));
flattened.forEach(System.out::println);
// Output: Java, Python, C++, JavaScript, Go, Ruby
Without Arrays.stream(), you'd have a Stream<String[]>, which keeps the nested structure. With it, you get a flat Stream<String>.
Why This Matters
Many APIs and data structures return arrays. When processing nested arrays in a stream pipeline, Arrays.stream() is your tool for converting each sub-array into a stream that flatMap can merge into one continuous sequence.
Key Takeaway: Use Arrays.stream() inside flatMap to convert array elements into streams, enabling you to flatten nested array structures into a single, unified stream.