CodeGym /Courses /JAVA 25 SELF /Safe removal of elements

Safe removal of elements

JAVA 25 SELF
Level 28, Lesson 2
Available

1. The ConcurrentModificationException problem

There’s (almost) nothing new in this lecture. But it’s very important, because careless data deletion is among the most irreparable mistakes — especially in production. And there will be one interesting class you’ll likely come to love!

So yes, once again and again: no for-each for deletion! No matter how much you love it.

Let’s start with a classic example that causes pain and suffering for many beginners (and not only them):

List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));

// Let's try to remove all even numbers
for (Integer n : numbers) {
    if (n % 2 == 0) {
        numbers.remove(n); // BOOM! ConcurrentModificationException
    }
}

It looks like it should work, but in reality the program throws an exception:

Exception in thread "main" java.util.ConcurrentModificationException

Now let’s look in more detail at what happened. When you iterate a collection using for-each (or a regular Iterator), the collection maintains a special “modification count”. If during iteration the collection changes not via the iterator itself, this counter detects “outside interference” and throws an exception. This protects against errors so the program doesn’t work with a corrupted data structure.

2. Using an Iterator

How do you correctly remove elements during iteration?

Reminder: an Iterator is a special object that lets you iterate over a collection and safely remove elements on the fly. It’s like a waiter who not only serves dishes but can also remove a plate right during the table round.

Getting an iterator

Iterator<Integer> it = numbers.iterator();

Iterating with while and removing via it.remove()

Here’s the correct way to remove all even numbers from a list:

List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));

Iterator<Integer> it = numbers.iterator();
while (it.hasNext()) {
    Integer n = it.next();
    if (n % 2 == 0) {
        it.remove(); // Safe removal of the current element
    }
}
System.out.println(numbers); // [1, 3, 5]

Important: you can only remove elements via the iterator itself (it.remove()) and only after calling it.next(). If you try to call remove() twice in a row without next(), you’ll get an IllegalStateException.

3. ListIterator: extended capabilities

Here’s the promised novelty from the start of the lecture! ListIterator is an “enhanced” iterator for lists (List) that allows not only removal but also adding elements during iteration, as well as moving in both directions (forward and backward).

Differences from a regular Iterator

  • Iterator — straightforward and unyielding: only forward, only removal.
  • ListIterator — flexible and mobile: forward and backward, removal, adding via add(), and you can also replace the current element with set().

Example: removing and adding elements

List<String> words = new ArrayList<>(List.of("cat", "dog", "bird"));

ListIterator<String> it = words.listIterator();
while (it.hasNext()) {
    String word = it.next();
    if (word.length() == 3) {
        it.remove(); // Remove 3-letter words
        it.add("pet"); // Immediately add "pet" after the removed word
    }
}
System.out.println(words); // [pet, pet, bird]

Note: adding via it.add() inserts the element immediately after the iterator’s current position.

4. Removing with removeIf

Starting with Java 8, the concise and convenient method removeIf was introduced. It takes a lambda expression (or any Predicate) and removes all elements for which the condition returns true.

Example: removing all even numbers

List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));

numbers.removeIf(n -> n % 2 == 0);

System.out.println(numbers); // [1, 3, 5]

It’s not only shorter but also safe: internally, the method uses the correct iterator — there will be no ConcurrentModificationException.

Example: removing strings shorter than 3 characters

List<String> words = new ArrayList<>(List.of("hi", "cat", "no", "elephant"));

words.removeIf(word -> word.length() < 3);

System.out.println(words); // [cat, elephant]

Tip: if you just need to remove elements by a condition, use removeIf. It’s the most concise and modern approach.

5. Practical recommendations

Which approach is preferable?

  • If you need to remove elements by a complex condition and you’re on Java 8+: use removeIf — short, clear, safe.
  • If you’re on an older Java version or need more complex iteration logic: use an Iterator and its remove() method.
  • If you work with a List and want not only to remove but also add elements during iteration: use a ListIterator.

Specifics for different collection types

  • List: supports all the approaches described (Iterator, ListIterator, removeIf).
  • Set: there are no indices, but the standard Iterator and removeIf work.
  • Map: to remove by condition, use an iterator over entrySet():
    Map<String, Integer> map = new HashMap<>(Map.of("a", 1, "b", 2, "c", 3));
    Iterator<Map.Entry<String, Integer>> it = map.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String, Integer> entry = it.next();
        if (entry.getValue() % 2 == 0) {
            it.remove();
        }
    }
    System.out.println(map); // {a=1, c=3}
    
    And with Java 8+ it becomes much simpler:
    map.entrySet().removeIf(entry -> entry.getValue() % 2 == 0);
    

6. Real-world example: filtering users

Suppose we have a list of users and we want to remove all users younger than 18.

class User {
    String name;
    int age;
    User(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
}

List<User> users = new ArrayList<>(List.of(
    new User("Alice", 17),
    new User("Bob", 20),
    new User("Victoria", 15),
    new User("George", 25)
));

// Remove minors via removeIf
users.removeIf(user -> user.age < 18);

System.out.println(users); // [Bob (20), George (25)]

7. Comparison of approaches

Let’s make a small table to reinforce. Our brain likes that.

Method Available since Conciseness Safety Flexibility
for-each + remove()
Java 5+ - ❌ -
Iterator + remove()
Java 5+ + ✅ +
ListIterator
Java 5+ + ✅ ++
removeIf
Java 8+ ++ ✅ +

8. Common mistakes when removing elements from collections

Mistake #1: attempting to remove elements in for-each

for (String s : list) {
    if (s.equals("test")) {
        list.remove(s); 
    }
}

You already know: don’t do this — you’ll get a ConcurrentModificationException! Use an iterator or removeIf.

Mistake #2: calling remove() on an iterator without next()

Iterator<String> it = list.iterator();
it.remove(); // IllegalStateException — cannot remove before calling next()

Mistake #3: attempting to remove elements from an unmodifiable collection

List<String> immutable = List.of("a", "b", "c");
immutable.removeIf(s -> s.equals("a")); // UnsupportedOperationException

Removal methods are not supported for unmodifiable collections.

Mistake #4: attempting to remove elements from a Map via values() or keySet() without an iterator

for (String key : map.keySet()) {
    if (key.startsWith("a")) {
        map.remove(key); // ConcurrentModificationException!
    }
}

Use an iterator over entrySet() or removeIf.

1
Task
JAVA 25 SELF, level 28, lesson 2
Locked
Reclassification of Pets at the "Friend" Pet Store 🐶
Reclassification of Pets at the "Friend" Pet Store 🐶
1
Task
JAVA 25 SELF, level 28, lesson 2
Locked
Cleaning the competition participants list from "suspicious" results 🏅
Cleaning the competition participants list from "suspicious" results 🏅
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION