The foreach
loop (or enhanced for
loop) does not have facilities to keep track of which element is being iterated on at the moment. There is no way to find out which index of a Collection
is being worked on, or whether there are more elements to be processed in an Iterable
.
That said, one workaround that would work is to keep a reference to the object which is being iterated on at the moment in the foreach
loop.
By keeping a reference of what it being worked on at the current iteration, one would be able to keep the reference once the foreach
loop ends, and what is left in the variable will be the last element.
This workaround will only work if-and-only-if the last element is the only element which is needed.
For example:
String lastString = null;
for (String s : new String[] {"a", "b", "c"}) {
// Do something.
// Keep the reference to the current object being iterated on.
lastString = s;
}
System.out.println(lastString);
Output:
c