How to iterate from last to first ArrayList?

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

+6
source share
5 answers

For now, you can always iterate over your ArrayList using an index, for example

 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 ListIterator<T> to remove 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 - for example:

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

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

+16
source

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

 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); } 
+7
source

If you just need to delete the last element of the array list, you can simply do:

 arrayList.remove(arrayList.size()-1); 

If you want to remove all elements from the back, you can use this for a loop:

 for(int i = arraList.size()-1; i >= 0; i--) { arrayList.remove(i); } 

For more information about array lists, you can go here: http://www.tutorialspoint.com/java/java_arraylist_class.htm

Hope this helps.

+1
source
 ArrayList aList = new ArrayList(); aList.add(1); aList.add(2); aList.add(3); Collections.reverse(aList); Iterator iter = aList.iterator(); while(iter.hasNext()){ iter.next(); iter.remove();//remove an element break;//break from the loop or something else } 
0
source
 List<String> names = .... int count= names.getSize(); Iterator<String> i = names.iterator(); while (i.hasNext()) { String s = i.next(); // must be called before you can call i.remove() // Do something if (count==1) i.remove(); count--; } 
0
source

Source: https://habr.com/ru/post/955442/


All Articles