Stream Creation Flashcards
Empty Stream with Stream.empty
Stream<String> emptyStream = Stream.empty();
The method itself does not inherently return a Stream<String> but rather an empty stream of a generic type <T> determined by context.
The compiler infers the type parameter <T> as String because of the variable declaration Stream<String>.</String></T></T></String></String>
From input array/list/var args using Stream.of()
Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9); //from var args</Integer>
Stream<Integer> stream = Stream.of( new Integer[]{1,2,3,4,5,6,7,8,9} ); //from array</Integer>
From Collections
List
List<String> list = Arrays.asList("A", "B", "C", "D")
Stream<String> stream = list.stream();</String></String>
Map
Stream<String> keyStream = map.keySet().stream();
Stream<Integer> valStream = map.values().stream();</Integer></String>
Arrays
String[] arr = { “A”, “B”, “C”, “D” };
Stream<String> stream = Arrays.stream(arr);</String>
Stream.Builder
The Stream.Builder class follows the builder pattern where we add items to the stream in steps, and finally call the method build() to get the stream.
Stream<String> streamBuilder = Stream.<String>builder()
.add("A")
.add("B")
.build();</String></String>
Infinite Streams iterate()
iterate(seed, function) – accepts two parameters – a seed which is the first term in the stream, and a function to produce the value of the next item in the stream. We can limit the stream using the limit() method.
Stream<Integer> infiniteEvenNumbers = Stream.iterate(0, n -> n + 2).limit(10);</Integer>
Infinite Streams generate()
generate(supplier) – accepts a Supplier that provides an infinite series of elements which are placed in the stream. The limit() method can then be called in the stream chain to stop the series after a certain number of elements.
Random rand = new Random();
Stream<Integer> stream =
Stream.generate(() -> rand.nextInt(100)).limit(20);</Integer>