andrew21
andrew21

Reputation: 23

How to delete last x element of a list after performing some operation on them?

i know how to iterate the last n element of a list using :

for(int i = list.size()-1; i>elements ; i --)
{
   list.element.get(i).makeSomeStuff();
   list.remove(list.element.get(i));
}

but i need to remove the elements from the list safely without messing around with the index

Upvotes: 0

Views: 103

Answers (2)

amram99
amram99

Reputation: 709

Use an Iterator instead of an indexed for loop if you need to remove elements from the collection (List in your case). See Remove entries from the list using iterator

Upvotes: 1

pleft
pleft

Reputation: 7905

The idea is to create a secondary list to hold the objects that you want to delete from the originating list.

List<MyObject> toBeRemovedList = new ArrayList()<>;
for(int i = list.size()-1; i>elements ; i --)
{
    MyObject myObject = list.get(i);
    myObject.makeSomeStuff();  //perform object action
    toBeRemovedList.add(myObject); //add the object into the removal list
}

list.removeAll(toBeRemovedList); //remove all the elements of the removal list from the originating list, no index interfering 

Upvotes: 2

Related Questions