Java 8 Stream Creation

Java 8 Streams are completely different than the streams related to File Input/Operations, like InputStream or FileInputStream as two examples. This is not that. So what is a Java 8 Stream?

Stream is a new abstract layer introduced in Java 8 version of the Java programming language. Java 8 introduced the concept of a stream that allows the developer process data declaratively.

You may still be asking yourself, what is a Java 8 Stream? Stated simply, streams are wrappers put around data that allows us to operate on that data source, which allows for fast bulk processing.

A stream does not store any data or modify any of the underlying data. Streams supports functional style operations on streams of elements, such as map-reduce transformations on collections.

Stream Creation

We can create a Java 8 Stream multiple ways that we will discuss below.

Create Stream From Array

After defining an array of Widgets, we create a Stream using the Stream.of() method.

private static Widget[] arrayOfWidgets = {
    new Widget(1, "Blue Widget", "blue"), 
    new Widget(2, "Green Widget", "green"), 
    new Widget(3, "Red Widget", "red")
};

Stream.of(arrayOfWidgets);


Create Stream From List

After defining a list of Widgets, we create a Stream using the List.stream() method. In Java 8, a new stream() method was added to the Collection Interface, which is then inherited by the List Interface.

private static List<Widget> widgetList = Arrays.asList(arrayOfWidgets);

widgetList.stream();


Create Stream From Objects

The Streams.of() method allows you to directly add objects to the Stream.

Stream.of(arrayOfWidgets[0], arrayOfWidgets[1], arrayOfWidgets[2]);


Create Stream Using Builder

The Stream.builder() method allows you to build a new Stream of objects.

Stream.Builder<Widget> widgetStreamBuilder = Stream.builder();

widgetStreamBuilder.accept(arrayOfWidgets[0]);
widgetStreamBuilder.accept(arrayOfWidgets[1]);
widgetStreamBuilder.accept(arrayOfWidgets[2]);

Stream<Widget> widgetStream = widgetStreamBuilder.build();


Create Stream of Integers

The IntStream Interface allows you to create a stream of integers. The IntStream.of() method will accepts a sequence of integers or the IntStream.range() will create a stream using integers from the start arg to the end arg.

IntStream.of(1, 2, 3, 5);
....
IntStream.range(1, 10);



Add a Comment

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