Since a few people asked for something like this, here are a few things you could do, although whether these are really better is arguable and a matter of taste:
void times(int n, Runnable r) {
for (int i = 0; i < n; i++) {
r.run();
}
}
Usage:
times(10, () -> System.out.println("Hello, world!"));
Or:
void times(int n, IntConsumer consumer) {
for (int i = 0; i < n; i++) {
consumer.accept(i);
}
}
Usage:
times(10, x -> System.out.println(x+1));
Or:
void range(int lo, int hi, IntConsumer consumer) {
for (int i = lo; i < hi; i++) {
consumer.accept(i);
}
}
Usage:
range(1, 11, x -> System.out.println(x));
These are just a few ideas. Designed thoughtfully, placed in a common library, and used consistently, they could make common, idiomatic code terse yet readable. Used carelessly, they could turn otherwise straightforward code into an unmanageable mess. I doubt any two developers would ever agree on exactly where the lines should be drawn.
doInRange(int max, IntConsumer whatToDo)
– Cacomistle