2024-03-19

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 java 8.

How to replace a on a finite set :

Before :


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

After :


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

How to replaceĀ a for loop :

Before :

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

After :

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

How to replace an infinite loop :

Before :

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

After:

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

 

Sylvain Leroy

Senior Software Quality Manager and Solution Architect in Switzerland, I have previously created my own company, Tocea, in Software Quality Assurance. Now I am offering my knowledge and services in a small IT Consulting company : Byoskill and a website www.byoskill.com Currently living in Lausanne (CH)

View all posts by Sylvain Leroy →