Skip to content

for comprehensions within a Stream

John McClean edited this page Jul 5, 2018 · 2 revisions

For-comprehensions

FutureStream and ReactiveSeq have a number of operators that make it easy to iterate simultaneously over multiple Streams generating a new Stream in the process - these are the various overloading versions of forEach2 & forEach3.

forEach2

Loop over two Streams (one containing 3 values another 10 to create a new Stream of 30 values)

FutureStream.of(1,2,3)
                 .forEach2(a->IntStream.range(0,10),
                         a->b-> a+b)
                 .toList()

//List[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 3, 4, 5, 6, 7, 8,
                         9, 10, 11, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)]

forEach2 with filter

We can also filter inside forEach2

FutureStream.of(2,3)
                 .forEach3(a->IntStream.range(6,9),
                           a->b->IntStream.range(100,105),
                           a->b->c -> a==3,
                           a->b->c-> a+b+c)

//List[109, 110, 111, 112, 113, 110, 111, 112, 113, 114, 111, 112, 113, 114, 115]

See also

Clone this wiki locally