Java Language Iterator and Iterable Removing elements using an iterator


The Iterator.remove() method is an optional method that removes the element returned by the previous call to For example, the following code populates a list of strings and then removes all of the empty strings.

List<String> names = new ArrayList<>();
names.add("name 1");
names.add("name 2");
names.add("name 3");
System.out.println("Old Size : " + names.size());
Iterator<String> it = names.iterator();
while (it.hasNext()) {
  String el =;
  if (el.equals("")) {
System.out.println("New Size : " + names.size());

Output :

Old Size : 5
New Size : 3

Note that is the code above is the safe way to remove elements while iterating a typical collection. If instead, you attempt to do remove elements from a collection like this:

for (String el: names) {
    if (el.equals("")) {
        names.remove(el); // WRONG!

a typical collection (such as ArrayList) which provides iterators with fail fast iterator semantics will throw a ConcurrentModificationException.

The remove() method can only called (once) following a next() call. If it is called before calling next() or if it is called twice following a next() call, then the remove() call will throw an IllegalStateException.

The remove operation is described as an optional operation; i.e. not all iterators will allow it. Examples where it is not supported include iterators for immutable collections, read-only views of collections, or fixed sized collections. If remove() is called when the iterator does not support removal, it will throw an UnsupportedOperationException.