4

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?

Vikram
  • 81
  • 1
  • 2
  • 5

2 Answers2

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
    Performance wise not Optimal and Wise ! – Ankur Anand Jun 16 '15 at 19:12
  • 1
    Actually 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
  • Guava Lists has a util to reverse without copy: Lists.reverse(letters) – tkruse Dec 18 '18 at 04:32
  • @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