I have two lists in Java. For one, i want to iterate from the beginning and for the other I want to start from the end. I wanted to use enhanced for loop for this, but i am unsure how to do that. Any suggestions?
Asked
Active
Viewed 9,507 times
4
-
1Firstly, you should try by your own. It isn't that complicated. – hpopiolkiewicz Jun 16 '15 at 19:03
-
1http://stackoverflow.com/questions/3962766/java-reverse-list – assylias Jun 16 '15 at 19:04
-
Why do you need to use the enhanced for loop? It makes the most common case really simple, but you still have the original for-loop to handle all the other, less frequent, cases. – Patricia Shanahan Jun 16 '15 at 19:17
2 Answers
7
No, you cannot use the Enhanced For-Loop to iterate from the end to the beginning of a List. Enhanced For-Loops should be used for simplicity when you wish to step through the elements in a first-to-last order. In any other cases, the "standard" For-Loop is the most optimal.

AngelTrs
- 236
- 1
- 8
5
You can create a copy of the list and reverse it:
List<T> listCopy = new ArrayList<T>(list);
Collections.reverse(listCopy);
for(T t : listCopy) {
...
}
You can also use a ListIterator
(the enhanced for loop uses an Iterator
in the background):
An iterator for lists that allows the programmer to traverse the list in either direction.

M A
- 71,713
- 13
- 134
- 174
-
3
-
1Actually the answer should be that there is no way to do exactly what the OP wants. Any workaround is not optimal. – M A Jun 16 '15 at 19:24
-
-
@tkruse That's a nice option, and it uses a custom `ListIterator` as I mentioned in the answer. Anyway I think you should write the Guava solution as an answer :) – M A Dec 19 '18 at 10:41
-
It's mentioned in both questions linked as related, this question really is a duplcate that should be closed, So I won't answer. Feel free to extend your answer though, – tkruse Dec 20 '18 at 07:12