0

Loop using lambdas and streams in Java 8 for lazy dude

Bookmark this on Hatena Bookmark
Share on LinkedIn
Pocket

A short article 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) {
 body
}

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 :

Before :

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

After:

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

 

Share on LinkedIn
Pocket

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 knowledges and services in a small IT Consulting company : Byoskill and a website www.byoskill.com Currently living in Lausanne (CH)