Skip to content

Java Stream creation methods

Java 8 introduced the Stream API as a means to process sequences of elements declaratively. Before performing operations like filtering or mapping, a Stream instance must be obtained from a data source.^[600-developer__java__java8__java8.md]

From Arrays

The Arrays utility class provides the stream() method to create streams from arrays. This method is overloaded for primitive types (int, long, double) and object types (String, etc.).^[600-developer__java__java8__java8.md]

java Arrays.stream(new int[] {1, 1, 2, 3, 5}); Arrays.stream(new long[] {1, 1, 2, 3, 5}); Arrays.stream(new double[] {1, 1, 2, 3, 5}); Arrays.stream(new String[] {"foo", "bar"});^[600-developer__java__java8__java8.md]

From Collections

All implementations of the Collection interface (e.g., List, Set) inherit the stream() method, which allows for the sequential creation of a Stream from the collection's elements.^[600-developer__java__java8__java8.md]

java Arrays.asList(1, 2, 3).stream();^[600-developer__java__java8__java8.md]

Static Factory Methods

The Stream interface itself offers several static utility methods for creating streams directly without an existing collection.

Stream.of()

This method creates a sequentially ordered stream from a specific set of values.^[600-developer__java__java8__java8.md]

java Stream.of(1, 2, 3); Stream.of(1);^[600-developer__java__java8__java8.md]

Stream.concat()

The concat method creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.^[600-developer__java__java8__java8.md]

java var s1 = Stream.of(1, 2, 3); var s2 = Stream.of(4, 5, 6); Stream.concat(s1 , s2);^[600-developer__java__java8__java8.md]

  • [[Functional Interfaces]]
  • [[Method References]]
  • [[Optional]]

Sources

  • 600-developer__java__java8__java8.md