How to Convert a Stream to Array in Java


In this example we will show how to convert a stream into an array.

Source Code

package com.beginner.examples;

import java.util.Arrays;

public class Stream2ArrayExample {

    public static void main(String[] args) {

        String str = "java example";

        // split by space
        String[] arr = Arrays.stream(str.split(" "))
			.toArray(String[]::new);

        //print the array
        for (String string : arr) {
            System.out.println(string);
        }

    }

}

Output:

java
example

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments