Creating a Stream
suggest changeEvery Java Collection<E> has stream() and parallelStream() methods that construct a Stream<E>:
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 = Arrays.stream(values);
Stream<String> stringStreamAlternative = Stream.of(values);
Stream.of() takes varargs, so it can be used like:
Stream<Integer> integerStream = Stream.of(1, 2, 3);
For a reference array, Stream.of(values) is a stream of the elements. For a primitive array, Stream.of(intArray) is a Stream<int[]> of one element. Use Arrays.stream or IntStream.of for the primitive values.
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 Arrays.stream() method:
IntStream intStream = Arrays.stream(new 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 intStream = Arrays.stream(values, 1, 3);
The range is half-open: index 1 inclusive through index 3 exclusive. Any primitive stream can be converted to a stream of boxed values with boxed:
Stream<Integer> integerStream = intStream.boxed();
This is useful when collecting, because a primitive stream has no collect method that takes a Collector.
Reusing intermediate operations of a stream chain
A stream cannot be reused after a terminal operation. That does not close it; close() is separate and is for releasing a stream's resources. To apply the same intermediate operations with different terminal operations, supply a new stream each time:
Supplier<Stream<String>> streamSupplier = () -> Stream.of("apple", "banana","orange", "grapes", "melon","blueberry","blackberry")
.map(String::toUpperCase).sorted();
streamSupplier.get().filter(s -> s.startsWith("A")).forEach(System.out::println);
// APPLE
streamSupplier.get().filter(s -> s.startsWith("B")).forEach(System.out::println);
// BANANA
// BLACKBERRY
// BLUEBERRY
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());