Creating a Stream

suggest change

All java Collection<E>s have stream() and parallelStream() methods from which a Stream<E> can be constructed:

Collection<String> stringList = new ArrayList<>();
Stream<String> stringStream = stringList.parallelStream();

A Stream<E> can be created from an array using one of two methods:

String[] values = { "aaa", "bbbb", "ddd", "cccc" };
Stream<String> stringStream =;
Stream<String> stringStreamAlternative = Stream.of(values);

The difference between and Stream.of() is that Stream.of() has a varargs parameter, so it can be used like:

Stream<Integer> integerStream = Stream.of(1, 2, 3);

There are also primitive Streams that you can use. For example:

IntStream intStream = IntStream.of(1, 2, 3);
DoubleStream doubleStream = DoubleStream.of(1.0, 2.0, 3.0);

These primitive streams can also be constructed using the method:

IntStream intStream = int[]{ 1, 2, 3 });

It is possible to create a Stream from an array with a specified range.

int[] values= new int[]{1, 2, 3, 4, 5};
IntStream intStram =, 1, 3);

Note that any primitive stream can be converted to boxed type stream using the boxed method :

Stream<Integer> integerStream = intStream.boxed();

This can be useful in some case if you want to collect the data since primitive stream does not have any collect method that takes a Collector as argument.

Reusing intermediate operations of a stream chain

Stream is closed when ever terminal operation is called. Reusing the stream of intermediate operations, when only terminal operation is only varying. we could create a stream supplier to construct a new stream with all intermediate operations already set up.

Supplier<Stream<String>> streamSupplier = () -> Stream.of("apple", "banana","orange", "grapes", "melon","blueberry","blackberry")

  streamSupplier.get().filter(s ->   s.startsWith("A")).forEach(System.out::println);


  streamSupplier.get().filter(s -> s.startsWith("B")).forEach(System.out::println);


int[] arrays can be converted to List<Integer> using streams

int[] ints = {1,2,3};
List<Integer> list = IntStream.of(ints).boxed().collect(Collectors.toList());

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents