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);