Java Stream toArray() with examples

 198 total views,  1 views today

Welcome to Java 8 series. In this tutorial, you will learn about java stream toArray() with examples.

toArray() is a part of the Stream pipeline and terminal operation. It belongs to the Stream interface.

toArray() allows us to get all elements of the stream as an array.  Once toArray() is invoked on a stream, it returns an array with elements of the stream and the stream will be closed. We cannot reuse the stream as we have invoked a terminal operation i.e., toArray().

Method Description

Object[] toArray()

Returns an array containing the elements of this stream.

Let us now see a few examples of Java 8 stream toArray()

Java stream toArray() operation example

public class StaticReference
{
    public static void main(String[] args)
    {
        List<Integer> list = new ArrayList<>();
        list.add(2);
        list.add(3);
        list.add(3);
        list.add(4);
        list.add(5);
        list.add(6);
        list.add(7);
        Object[] result = list.stream().toArray();

        System.out.println(Arrays.toString(result));
    }
}

Output

[2, 3, 3, 4, 5, 6, 7]

Java stream toArray() operation example – String

public class StaticReference
{
    public static void main(String[] args)
    {

        List<String> listString = new ArrayList<>();
        listString.add("q");
        listString.add("b");
        listString.add("c");
        listString.add("d");
        Object[] result = listString.stream().toArray();

        System.out.println(Arrays.toString(result));
    }
}

Output

[q, b, c, d]

Conclusion

toArray() operation is a terminal operation and it is used for getting an array containing the elements of the stream.

References : Official documentation

Thanks for reading. Please a comment and give us a thumbs up! 

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.