Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shorter way to write a for loop in Java?

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.

like image 730
user30189 Avatar asked Feb 06 '17 21:02

user30189


4 Answers

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);
}
like image 94
Abdulgood89 Avatar answered Sep 20 '22 06:09

Abdulgood89


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.

like image 22
David Conrad Avatar answered Sep 23 '22 06:09

David Conrad


If you use Java 8, you can use IntStream.range(min, max).foreach(i ->{})

like image 33
Piotrowy Avatar answered Sep 22 '22 06:09

Piotrowy


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.

like image 40
FRanklinDavid Avatar answered Sep 21 '22 06:09

FRanklinDavid