Possible Duplicate:
Can one do a for each loop in java in reverse order?
For a forward iteration:
for (int i=0; i<pathElements.length; i++){
T pathElem = pathElements[i];
.......
}
I can code it as a foreach:
for(T pathElem : pathElements){
.......
}
Is there a switch so that a foreach could iterate in reverse?
for (int i=pathElements.length-1; i>=0; i--){
T pathElem = pathElements[i];
.......
}
Is there a reverse iteration switch in foreach?
(If not, don't you think it would be an exciting idea that JDK 8, 9, etc, includes this feature?)
It's fundamentally impossible because the foreach loop is based on the Iterable
and Iterator
interfaces, and those don't have a notion of reverse iteration.
Using Guava:
for (T elem : Lists.reverse(Arrays.asList(array))) {
...
}
iterates over a reversed view of the array as a list. (So there's only a constant overhead, and you don't change the underlying array.)
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