Stream Creation Flashcards

1
Q

Empty Stream with Stream.empty

A

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>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

From input array/list/var args using Stream.of()

A

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>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

From Collections

A

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>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Stream.Builder

A

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>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Infinite Streams iterate()

A

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>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Infinite Streams generate()

A

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>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly