Is there a way in Java's for-each loop
for(String s : stringArray) {
doSomethingWith(s);
}
to find out how often the loop has already been processed?
Aside from using the old and well-known for(int i=0; i < boundary; i++)
- loop, is the construct
int i = 0;
for(String s : stringArray) {
doSomethingWith(s);
i++;
}
the only way to have such a counter available in a for-each loop?
Using lambdas and functional interfaces in Java 8 makes creating new loop abstractions possible. I can loop over a collection with the index and the collection size:
Which outputs:
Which I implemented as:
The possibilities are endless. For example, I create an abstraction that uses a special function just for the first element:
Which prints a comma separated list correctly:
Which I implemented as:
Libraries will begin to pop up to do these sorts of things, or you can roll your own.
There is a "variant" to pax' answer... ;-)
The easiest solution is to just run your own counter thus:
The reason for this is because there's no actual guarantee that items in a collection (which that variant of
for
iterates over) even have an index, or even have a defined order (some collections may change the order when you add or remove elements).See for example, the following code:
When you run that, you can see something like:
indicating that, rightly so, order is not considered a salient feature of a set.
There are other ways to do it without a manual counter but it's a fair bit of work for dubious benefit.
If you need a counter in an for-each loop you have to count yourself. There is no built in counter as far as I know.
For situations where I only need the index occasionally, like in a catch clause, I will sometimes use indexOf.
I found that using a simple for loop with an incrementing index was the most efficient, reliable solution, as posted here: https://stackoverflow.com/a/3431543/2430549