Loop using lambdas and streams in Java 8 for lazy dude

A short to complete the page of MkYoung about the streams (link here).

How to write loops using and streams without using for ?

Answer : easy

These are my ways to write silly lazy loops using the for statement using .

How to replace a on a finite set :

Before :

List finiteSet = Lists.newArrayList(1,2,3,4);
for (Integer value : finiteSet) {

After :

        IntStream.of(1, 2, 3, 4).forEach(
            val -> body);

How to replace a :

Before :

for (int i = min, i < max; ++i) { body }

After :

IntStream.range(min, max).forEach(i-> body);

How to replace an :

Before :

int val= min; while(true) { val++; body}


IntStream.iterate(min, (x) -> x++).forEach(val -> body);


Related Posts