Inspired by Adam Bien's weblog I wanted to replace a common iteration in Java 7 into a nicer one in Java 8. The older code looked like this:
void repeatUsingJava7(int times) {
for (int i = 0; i < times; i++) {
doStuff();
doMoreStuff();
doEvenMoreStuff();
}
}
...which is not too nice. So I replaced it using Adam Bein's example into this:
void repeatUsingJava8(int times) {
IntStream.range(0, times).forEach(
i -> {
doStuff();
doMoreStuff();
doEvenMoreStuff();
}
);
}
...which is a step in the right direction, but does not make the code much simpler to read, and also introduces an unneeded variable i
, as well as an extra pair of curly brackets. So now I'm wondering if there are other ways to write this code which will make it even nicer and easier to read, primarily using Java 8.