Java 8 - Create Stream Object from Arrays Example

In this source code example, we will see how to use Java 8 stream API to create a Stream instance from an Array with an example.

Creating a Stream object from Arrays

Array can be a source of a Stream or Array can be created from the existing array or of a part of an array:
import java.io.IOException;
import java.util.Arrays;
import java.util.stream.Stream;

public class StreamCreationExamples {
    public static void main(String[] args) throws IOException {

        // Array can also be a source of a Stream
        Stream<String> streamOfArray = Stream.of("a", "b", "c");
        streamOfArray.forEach(System.out::println);

        // creating from existing array or of a part of an array:
        String[] arr = new String[] { "a", "b", "c" };
        Stream<String> streamOfArrayFull = Arrays.stream(arr);
        streamOfArrayFull.forEach(System.out::println);

        Stream<String> streamOfArrayPart = Arrays.stream(arr, 1, 3);
        streamOfArrayPart.forEach(System.out::println);
    }
}
Output:
a
b
c
a
b
c
b
c

Reference



Comments