Share on LinkedIn
Pocket

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

How to write loops using lambdas 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 loop 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);

 

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.comCurrently living in Lausanne (CH)

Optimization WordPress Plugins & Solutions by W3 EDGE