Java 8 Stream toArray Sample

Java 8 Stream toArray operation will return an array containing the elements of the Stream. Th Steam can be Integer, String, Char, or any other Java primitive data type.

The Stream.toArray() has the following syntax: Object[] toArray()

toArray() Stream of Integers

//JavaCodeDepot Sample

//Define our Stream of Integers
Stream<Integer> jcdIntStream = Stream.of(10, 20, 30, 40, 50);
 
//Invoke the Stream.toArray Operation
Object[] jcdIntArray = jcdIntStream.toArray();
 
//Print out our Array
System.out.println(Arrays.toString(jcdIntArray));

Output:

[10, 20, 30, 40, 50]


toArray() Stream of Strings

//JavaCodeDepot Sample

//Define our Stream of Strings
Stream<String> jcdStrStream = Stream.of("Java", "Code", "Depot", "Samples", "Tutorials");
 
//Invoke the Stream.toArray Operation
Object[] jcdStrArray = jcdStrStream.toArray();
 
//Print out our Array
System.out.println(Arrays.toString(jcdStrArray));

Output:

[Java, Code, Depot, Samples, Tutorials]


toArray() Stream of Strings Single Line

You can save a few lines by combining Stream.of() with toArray() as shown in the sample below.

//JavaCodeDepot Sample

Object[] jcdStrArray2 = Stream.of("Java", "Code", "Depot", "Samples", "Tutorials").toArray();
System.out.println(Arrays.toString(jcdStrArray));

Output:

[Java, Code, Depot, Samples, Tutorials]


I think you will find the Stream.toArray() operation of Java 8 to be very useful in your everyday Java programming activities.

Add a Comment

Your email address will not be published. Required fields are marked *