Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate from last to first an ArrayList?

I wonder if is possible to iterate from last to the first element in an ArrayList, if so how? The reason is because I need to remove the last element added to the list

like image 749
Ricardo Sanchez Avatar asked Oct 07 '13 19:10

Ricardo Sanchez


2 Answers

While you can always iterate your ArrayList using an index, like this

List<String> myList = new ArrayList<String>();
... add code to populate the list with some data...
for (int i = myList.size() - 1 ; i >= 0 ; i--) {
    if (myList.get(i).equals("delete me")) {
        myList.remove(i);
    }
}

you would be better off using a ListIterator<T> for the purpose of deleting items from your ArrayList:

ListIterator<String> listIter = myList.listIterator();
while (listIter.hasNext()) {
    if (listIter.next().equals("delete me")) {
        listIter.remove();
    }
}

List iterators can be used to iterate your list backwards, too -- like this:

ListIterator<String> listIter = myList.listIterator(myList.size());
while (listIter.hasPrevious()) {
    String prev = listIter.previous();
    // Do something with prev here
}

The initial index of the iterator should be equal to the index of the last element + 1. As the docs say: "An initial call to previous would return the element with the specified index minus one."

like image 99
Sergey Kalinichenko Avatar answered Sep 18 '22 00:09

Sergey Kalinichenko


Here is one way to do it (your reason why is a separate question):

import java.util.*;

List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");

ListIterator<String> iter = list.listIterator(list.size());

while (iter.hasPrevious()) {
    String s = iter.previous();
    System.out.println(s);
}
like image 36
Michael Easter Avatar answered Sep 18 '22 00:09

Michael Easter