0

I have the following code

final List<ItemDto> itemDtos = result.getResults();
List<String> deleteItemIds = new ArrayList<String>();

// remove items which have been deleted on the server
for(ItemDto itemDto : itemDtos) {
  if (itemDto.getIsRemoved()) {
    deleteItemIds.add(itemDto.getId());
    itemDtos.remove(itemDto);  //  TODO not sure if this works here
  }
}

I iterate over the itemDtos and remove an ItemDto at the last operation in the for loop. I think that this works if I do not need something like itemDtos.indexOf(o)inside the loop.

Is the code I did correctly working?

Edit: Here is a second variant:

List<ItemDto> itemDtos = result.getResults();
List<ItemDto> tmpList = itemDtos;
List<String> deleteItemIds = new ArrayList<String>();

// remove items which have been deleted on the server
for(ItemDto itemDto : tmpList) {
  if (itemDto.getIsRemoved()) {
    deleteItemIds.add(itemDto.getId());
    itemDtos.remove(itemDto);  //  TODO not sure if this works here
  }
}

Is the second variant better?

Michael
  • 32,527
  • 49
  • 210
  • 370
  • This throws concurrent item modification exception right? – Rohith K Jan 06 '15 at 14:35
  • to remove items from a list while iterating through it you should use an iterator and use the iterator.remove method – Frederic Close Jan 06 '15 at 14:37
  • 2
    Perhaps ... why don't you tell us? Write a unit test and see whether it works the way you expect it to. ;) – Steve Jan 06 '15 at 14:37
  • Take a look at this post: http://stackoverflow.com/questions/223918/iterating-through-a-list-avoiding-concurrentmodificationexception-when-removing – Ali Lotfi Jan 06 '15 at 14:37

2 Answers2

3

To safely remove elements from a list you should use the Iterator of the list like this:

for (Iterator<ItemDto> iterator = itemDtos.iterator(); iterator.hasNext()) {
    ItemDto itemDto = iterator.next();
    if (itemDto.getIsRemoved()) {
        deleteItemIds.add(itemDto.getId());
        iterator.remove(); 
    }
}
Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
marczeeee
  • 181
  • 1
  • 13
0

You can not remove object from a list when you perform a loop on this last. But you can use the iterators.

    Iterator<ItemDto> iterator = arrayList.iterator();
    while (iterator.hasNext()) {
        ItemDto item = iterator.next();
        //Do your job
        iterator.remove();
    }

A second solution could be to loop a first time to find all the elements to delete, store them within a list, and then remove them from the first list thank to List.removeAll.

tetienne
  • 369
  • 3
  • 13