671

In Java, is it legal to call remove on a collection when iterating through the collection using a foreach loop? For instance:

List<String> names = ....
for (String name : names) {
   // Do something
   names.remove(name).
}

As an addendum, is it legal to remove items that have not been iterated over yet? For instance,

//Assume that the names list as duplicate entries
List<String> names = ....
for (String name : names) {
    // Do something
    while (names.remove(name));
}
James McMahon
  • 48,506
  • 64
  • 207
  • 283
Michael Bobick
  • 8,897
  • 5
  • 22
  • 13
  • 34
    Not a great plan. Just because the language tolerates it on any given run, doesn't make it a good idea. – Mark McKenna Nov 01 '11 at 12:57
  • You must've caught me in a bad mood, but seems to me the answer to this question comes straight out of the foreach documentation. – CurtainDog Jun 25 '12 at 11:47
  • 2
    http://stackoverflow.com/questions/223918/efficient-equivalent-for-removing-elements-while-iterating-the-collection – Jeevi Oct 18 '12 at 18:29
  • 1
    As an alternative, you might consider not modifying your collection in-place but use a filtering combinator such as Guava's Iterables#filter: http://code.google.com/p/guava-libraries/wiki/FunctionalExplained Be aware of its lazy behavior! – thSoft Dec 17 '12 at 15:12
  • Did you really intend to ask about `Collection` specifically, rather than `List` which you use in your code? If you intended to ask about `List` and not `Collection`, then please edit this question to reflect that - then this question would not be a duplicate! (One big difference of `List` vs `Collection` is that `List` includes `get` in its interface, while `Collection` does not). – cellepo Dec 19 '18 at 22:49
  • You can use removeIf method. Example: sockets.removeIf(Socket::isClosed); – Enginer May 26 '21 at 17:41

11 Answers11

1026

To safely remove from a collection while iterating over it you should use an Iterator.

For example:

List<String> names = ....
Iterator<String> i = names.iterator();
while (i.hasNext()) {
   String s = i.next(); // must be called before you can call i.remove()
   // Do something
   i.remove();
}

From the Java Documentation :

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Perhaps what is unclear to many novices is the fact that iterating over a list using the for/foreach constructs implicitly creates an iterator which is necessarily inaccessible. This info can be found here

mphizi
  • 13
  • 2
Mark
  • 28,783
  • 8
  • 63
  • 92
  • 42
    Note that you must call i.next() before you can call i.remove(): [docs.oracle.com/javase/6/docs/api/java/util/Iterator.html](http://docs.oracle.com/javase/6/docs/api/java/util/Iterator.html#remove()) – John Mellor Mar 07 '12 at 15:18
  • 13
    I'm curious, why is this considered safe? Is the `Iterator` acting as middle man? – James P. May 12 '12 at 22:02
  • I second James's question. What about that method is better? – Ethan Reesor Jun 20 '12 at 20:22
  • 22
    To quote the Javadoc for Iterator.remove() "The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method." The iterator is acting as a middle man to safely perform the removal but allow the iteration to continue as expected. – Mark Jun 25 '12 at 11:22
  • 7
    but worth noting that the remove() method is OPTIONAL on an iterator and will throw exceptions if it isn't implemented for your particular collection or JVM –  Jun 12 '13 at 17:33
  • FYI you can call `it.next()` in if statment instead of the sample above -- or you can do as the code above – shareef Jun 17 '13 at 09:39
  • I get the idea but based on isn't this all happening in one thread though? ConcurrentModificationException would make more sense if there was thread acting on the data structure. – committedandroider Mar 22 '15 at 06:42
  • 1
    @committedandroider From the Javadoc for ConcurrentModificationException `Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception. ` – Mark Mar 22 '15 at 22:18
  • @Mark, But why java has designed only iterator to remove element. This could have been done for each loop also? – Sumit Gupta Apr 11 '17 at 10:24
  • as of Java 8 you can actually use: **names.removeIf( t -> t )** – Serafins Sep 19 '19 at 12:42
180

You don't want to do that. It can cause undefined behavior depending on the collection. You want to use an Iterator directly. Although the for each construct is syntactic sugar and is really using an iterator, it hides it from your code so you can't access it to call Iterator.remove.

The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.

Instead write your code:

List<String> names = ....
Iterator<String> it = names.iterator();
while (it.hasNext()) {

    String name = it.next();
    // Do something
    it.remove();
}

Note that the code calls Iterator.remove, not List.remove.

Addendum:

Even if you are removing an element that has not been iterated over yet, you still don't want to modify the collection and then use the Iterator. It might modify the collection in a way that is surprising and affects future operations on the Iterator.

Jared Oberhaus
  • 14,547
  • 4
  • 56
  • 55
  • 5
    Thumbs up for the extra Note *that the code calls Iterator.remove, not List.remove". I almost missed and used list.remove – pratpor Sep 12 '19 at 11:56
96
for (String name : new ArrayList<String>(names)) {
    // Do something
    names.remove(nameToRemove);
}

You clone the list names and iterate through the clone while you remove from the original list. A bit cleaner than the top answer.

Chin
  • 19,717
  • 37
  • 107
  • 164
ktamlyn
  • 4,519
  • 2
  • 30
  • 41
  • 3
    this supposed to be the first answer here... – itzhar Aug 26 '15 at 10:45
  • 4
    Beware. For composite objects with no equals and hashCode method, it might just fail. However, marked answer safely removes it. – D3V Dec 28 '15 at 14:54
  • 28
    Though short and clean, if performance/memory usage are an issue, it is worth to note that this solution runs in O(n²) and creates a copy of the original list, which requires memory and an operation depending on the type of the list. Using an iterator over a LinkedList you can bring complexity down to O(n). – SND Dec 15 '17 at 07:53
  • 2
    @SND Why would it be n^2? Creating copy of the list is O(n), therefore this is O(n) as well. – FINDarkside Apr 16 '19 at 17:43
  • 3
    @FINDarkside the O(n^2) doesn't come from creating a copy, but looping through the ArrayList (O(n)) while calling remove() on each element (also O(n)). – chakwok May 21 '19 at 18:40
74

The java design of the "enhanced for loop" was to not expose the iterator to code, but the only way to safely remove an item is to access the iterator. So in this case you have to do it old school:

 for(Iterator<String> i = names.iterator(); i.hasNext();) {
       String name = i.next();
       //Do Something
       i.remove();
 }

If in the real code the enhanced for loop is really worth it, then you could add the items to a temporary collection and call removeAll on the list after the loop.

EDIT (re addendum): No, changing the list in any way outside the iterator.remove() method while iterating will cause problems. The only way around this is to use a CopyOnWriteArrayList, but that is really intended for concurrency issues.

The cheapest (in terms of lines of code) way to remove duplicates is to dump the list into a LinkedHashSet (and then back into a List if you need). This preserves insertion order while removing duplicates.

Yishai
  • 90,445
  • 31
  • 189
  • 263
  • Although `CopyOnWriteArrayList` will avoid `ConcurrentModificationException`, there could still be other indexing problems/Exceptions ([more details](https://stackoverflow.com/a/37990142/1357094)). – cellepo Dec 20 '18 at 01:23
35

I didn't know about iterators, however here's what I was doing until today to remove elements from a list inside a loop:

List<String> names = .... 
for (i=names.size()-1;i>=0;i--) {    
    // Do something    
    names.remove(i);
} 

This is always working, and could be used in other languages or structs not supporting iterators.

Niko
  • 26,516
  • 9
  • 93
  • 110
Serafeim
  • 14,962
  • 14
  • 91
  • 133
  • 2
    Just as a side-note, that should work fine with any base-class list, but wouldn't be portable to more esoteric structures (like a self-sorting sequence, for example--in general, anywhere the ordinal for a given entry could change between list iterations). – Mark McKenna Nov 01 '11 at 13:01
  • 8
    Note: this works precisely because you're iterating backwords over the elements, so the indexes of the other remaining elements don't change when you remove the `i`th element. If you were looping from 0 to `size()-1`, and doing the remove, you'd see the issues mentioned in other answers. Nice job, though! – Jake Toronto Sep 24 '14 at 04:46
  • This is just a horrible way to do. So many things can go wrong depending on the implementation of the List (or Set, etc.). – DavidR Nov 29 '16 at 02:21
  • 2
    Such indexed based operations should only be conducted on lists whose elements can be accessed in O(1) constant time. If the list is not randomly accessible (does not implement RandomAccess) then you should use an iterator instead, as these types of collections usually take longer to retrieve an element at a specific index position, such as a LinkedList. – TheArchon Feb 04 '17 at 02:45
  • As long as we're working with Java collections, where we do have iterators, there is no advantage to this method -- it only adds potential for really difficult debugging – forresthopkinsa Oct 18 '17 at 19:45
  • 2
    The advantage of the above method is that you (or at least most people) don't have to google for "java iterator example" but can write it immediately, by memory. – Serafeim Oct 18 '17 at 20:49
  • [Analogous code that _iterates from beginning_](https://stackoverflow.com/a/43441822/1357094) (increments `i` instead conditionally in body, which I believe alleviates most if not all other concerns). – cellepo Dec 20 '18 at 00:39
  • Either way, these types of Answers exhibit that it's particularly the _enhanced_-for-loop that will throw `ConcurrentModificationException` - _not_ the _traditional_-for-loop (although as mentioned, extra care must be taken with its incrementing). – cellepo Dec 20 '18 at 00:44
28

Yes you can use the for-each loop, To do that you have to maintain a separate list to hold removing items and then remove that list from names list using removeAll() method,

List<String> names = ....

// introduce a separate list to hold removing items
List<String> toRemove= new ArrayList<String>();

for (String name : names) {
   // Do something: perform conditional checks
   toRemove.add(name);
}    
names.removeAll(toRemove);

// now names list holds expected values
Chathuranga Withana
  • 862
  • 1
  • 9
  • 12
  • 2
    Why add the overhead of another list ? – Varun Mehta Jan 25 '11 at 03:31
  • 2
    Since the `for-each` loop hides the `iterator`, you cannot call the `remove()` directly. So in order to remove items from a `for-each` loop while iterating through it, have to maintain a separate list. That list will maintain references to the items to be removed... – Chathuranga Withana Mar 19 '11 at 18:44
  • 1
    Its very slow. removeAll 1. runs contains() on every toRemove element 2. then runs remove() which has to find element index so need to again look through whole list. – mmatloka Jan 04 '12 at 13:39
  • this isn't calling remove() in a foreach loop –  Jun 12 '13 at 17:36
5

Make sure this is not code smell. Is it possible to reverse the logic and be 'inclusive' rather than 'exclusive'?

List<String> names = ....
List<String> reducedNames = ....
for (String name : names) {
   // Do something
   if (conditionToIncludeMet)
       reducedNames.add(name);
}
return reducedNames;

The situation that led me to this page involved old code that looped through a List using indecies to remove elements from the List. I wanted to refactor it to use the foreach style.

It looped through an entire list of elements to verify which ones the user had permission to access, and removed the ones that didn't have permission from the list.

List<Service> services = ...
for (int i=0; i<services.size(); i++) {
    if (!isServicePermitted(user, services.get(i)))
         services.remove(i);
}

To reverse this and not use the remove:

List<Service> services = ...
List<Service> permittedServices = ...
for (Service service:services) {
    if (isServicePermitted(user, service))
         permittedServices.add(service);
}
return permittedServices;

When would "remove" be preferred? One consideration is if gien a large list or expensive "add", combined with only a few removed compared to the list size. It might be more efficient to only do a few removes rather than a great many adds. But in my case the situation did not merit such an optimization.

bmcdonald
  • 311
  • 6
  • 12
4

Those saying that you can't safely remove an item from a collection except through the Iterator aren't quite correct, you can do it safely using one of the concurrent collections such as ConcurrentHashMap.

sanity
  • 35,347
  • 40
  • 135
  • 226
  • Although it will avoid `ConcurrentModificationException`, there could still be other indexing problems/Exceptions ([more details](https://stackoverflow.com/a/37990142/1357094)). – cellepo Dec 20 '18 at 01:22
1
  1. Try this 2. and change the condition to "WINTER" and you will wonder:
public static void main(String[] args) {
  Season.add("Frühling");
  Season.add("Sommer");
  Season.add("Herbst");
  Season.add("WINTER");
  for (String s : Season) {
   if(!s.equals("Sommer")) {
    System.out.println(s);
    continue;
   }
   Season.remove("Frühling");
  }
 }
Grzegorz Rożniecki
  • 27,415
  • 11
  • 90
  • 112
Carsten
  • 19
  • 1
1

It's better to use an Iterator when you want to remove element from a list

because the source code of remove is

if (numMoved > 0)
    System.arraycopy(elementData, index+1, elementData, index,
             numMoved);
elementData[--size] = null;

so ,if you remove an element from the list, the list will be restructure ,the other element's index will be changed, this can result something that you want to happened.

song
  • 19
  • 3
-5

Use

.remove() of Interator or

Use

CopyOnWriteArrayList

ThmHarsh
  • 601
  • 7
  • 7