Explain Codes LogoExplain Codes Logo

How to convert a Java 8 Stream to an Array?

java
java-8
streams
performance
Nikita BarsukovbyNikita Barsukov·Aug 11, 2024
TLDR

You can convert a Java 8 Stream into an array effortlessly with the Stream.toArray(Generator) method, as follows:

Stream<Integer> stream = Stream.of(1, 2, 3); Integer[] array = stream.toArray(Integer[]::new); // For objects IntStream intStream = IntStream.of(1, 2, 3); int[] intArray = intStream.toArray(); // For primitives

The main takeaway: Use toArray(Generator) for object streams, and toArray() directly for primitive streams.

Handling Custom Array types

Take a look at how you can convert a custom array types. It's pretty similar to the previous section:

Stream<YourClass> customStream = ...; YourClass[] customArray = customStream.toArray(YourClass[]::new);

Here 'YourClass[]::new' is a method reference that creates a new array, working as a neat alternative to lengthy lambda expressions.

Mapping and Filtering Streams

Leverage indispensable Stream operations to modify data before converting it to an array:

// Balloons inflate, right? So do Strings. Inflate them to uppercase. String[] upperCaseArray = stream .map(String::toUpperCase) .toArray(String[]::new); // Shave off unwanted space, just like trimming your beard. String[] trimmedArray = stream .map(String::trim) .toArray(String[]::new);

Primitive Streams to Arrays

For IntStream or other primitive streams, conversion to an array's a piece of cake:

// Turning up the heat now. An array straight from 1 to 10. IntStream intStream = IntStream.rangeClosed(1, 10); int[] primitiveArray = intStream.toArray(); // No assembly required.

IntStream.toArray() yields an int[] array. Use .boxed() to revert a primitive stream back to an object stream:

int[] primitiveArray = {1, 2, 3, 4}; Stream<Integer> boxedStream = Arrays.stream(primitiveArray).boxed(); // Bubbles aren't the only things that can be boxed.

Printing the Array

The forEach() method with System.out::println help print the elements of an array. It's like a free lecture on debugging.

Arrays.stream(array).forEach(System.out::println);

IntFunction for Complex Type Conversion

Let's understand the concept of IntFunction interface for complex type conversions:

Stream<String> stream = ...; // Complex string steam, maybe a poem? SomeComplexType[] complexArray = stream.toArray(SomeComplexType[]::new); // Bam! Poem's now a complex array.

From CSV to Stream to Array

Ever had a comma-separated string and dreamt of a stream, then an array? Say no more:

String line = "apple,banana,carrot"; // So fresh, so clean. Stream<String> initialStream = Arrays.stream(line.split(",")); // An array of fruits? More like a fruit salad.

Then, convert the Stream to the desired array type.

List to Array

Love lists but need an array? This example has got you covered:

List<String> list = Arrays.asList("one", "two", "three"); String[] arrayFromList = list.stream().toArray(String[]::new); // One, two, three and we're done.

Generics in Java

Working with generic streams? Here's how to ensure type safety:

Stream<T> genericStream = ...; // Generic, like your favorite brand. T[] genericArray = genericStream.toArray(size -> (T[])new Object[size]); // Arrays are now on-brand too.

Optimal Conversion Efficiency

Understand performance implications of stream operations. Use the force of pipelining:

YourClass[] efficientArray = stream .filter(e -> e.meetsCondition()) // Filtering is not just for coffee .sorted() // Sorting like it's going out of style .toArray(YourClass[]::new); // Ta-da! An array. What's my prize?

Anonymous Classes at Aid

Who says traditional anonymous inner classes are out of place? They provide very clear syntax:

String[] array = stream.toArray(new IntFunction<String[]>() { @Override public String[] apply(int value) { return new String[value]; // Doing it old-school. Because old is gold. } });

Though more verbose, they are the savior in complex scenarios.