Java Stream toArray() Example

In this tutorial, we will learn Java 8 Stream toArray() terminal operation with an example.

The Java Stream toArray() method is a terminal operation that starts the internal iteration of the elements in the stream and returns an array of Objects containing all the elements. 

Java Stream toArray() Example

Here is a Java Stream toArray() example:

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args)
    {
        List<String> stringList = new ArrayList<>();

        stringList.add("one");
        stringList.add("two");
        stringList.add("three");
        stringList.add("four");

        Stream<String> stream = stringList.stream();

        Object[] objects = stream.toArray();

        System.out.println(objects[0]);
        System.out.println(objects[1]);
        System.out.println(objects[2]);
        System.out.println(objects[3]);
    }
}

Output:

one
two
three
four

Java Stream Methods/APIs Examples


Comments