Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java reverse foreach [duplicate]

Tags:

java

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?)

like image 345
Blessed Geek Avatar asked Feb 17 '12 15:02

Blessed Geek


2 Answers

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.

like image 57
Michael Borgwardt Avatar answered Oct 19 '22 16:10

Michael Borgwardt


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.)

like image 33
Louis Wasserman Avatar answered Oct 19 '22 17:10

Louis Wasserman