the code is
for(int i = 0; i < max; i++) {
//do something
}
I use this exact code many times when I program, always starting at 0 and using the interval i++. There is really only one variable that changes (max)
It could not be that much shorter, but considering how much this code is used, it would be quite helpful.
I know in python there is the range function which is much quicker to type.
When looping through collections, you can use enhanced loops:
int[] numbers =
{1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println(item);
}
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.
If you use Java 8, you can use IntStream.range(min, max).foreach(i ->{})
There is a way to write shorter for loop.
If "for" loop is the concern, you may find this interesting
for(int i = -1; ++i < max;) {
//do something
}
Notice that the counter increment was done before the comparison with max is done.
Also notice that the index i starts from -1 instead of normal 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With