Java Language Iterator and Iterable Removing elements using an iterator

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

The Iterator.remove() method is an optional method that removes the element returned by the previous call to Iterator.next(). 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("");
names.add("name 3");
names.add("");
System.out.println("Old Size : " + names.size());
Iterator<String> it = names.iterator();
while (it.hasNext()) {
  String el = it.next();
  if (el.equals("")) {
    it.remove();
  }
}
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.



Got any Java Language Question?