AI Hints
Home›Java Tutorial›Sorting with Comparator, Removing While Looping, Practice: Word Counter
Java · Lesson 89 of 120

Removing While Looping

The safe way.

⏱ 2 min read▶ Video at 1:52:55🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Removing items from a list, while a for each loop is walking through it, confuses the loop. Java stops you with an exception. Let's see the safe ways.

  • Remove during for-each?
  • Java stops you
  • Two safe ways

The problem

We try to remove the negative numbers, inside a for each loop. Run it. Concurrent modification exception. The list changed under the loop's feet.

Main.javajava
import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<Integer> nums = new ArrayList<>(List.of(5, -2, 8, -7, 3));
        for (Integer n : nums) {
            if (n < 0) nums.remove(n);
        }
    }
}
Output
Exception in thread "main" java.util.ConcurrentModificationException
    at Main.main(Main.java:5)

Two safe ways

An iterator walks the list for us. Has next asks if there's another item. Next gives it, and iterator remove removes it safely. Even shorter, remove if removes every item that matches a rule. The arrow is a small function, called a lambda. More on that soon. Run it. Both lists lose their negative numbers.

Main.javajava
import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<Integer> nums = new ArrayList<>(List.of(5, -2, 8, -7, 3));
        Iterator<Integer> it = nums.iterator();
        while (it.hasNext()) {
            if (it.next() < 0) it.remove();
        }
        System.out.println("With an iterator: " + nums);

        List<Integer> more = new ArrayList<>(List.of(4, -1, 6, -9));
        more.removeIf(n -> n < 0);
        System.out.println("With removeIf:    " + more);
    }
}
Output
With an iterator: [5, 8, 3]
With removeIf:    [4, 6]

Summary

Don't remove items inside a for each loop. Use an iterator, or remove if, instead. Next, a practice word counter.

Key takeaways
  • No remove in for-each
  • Iterator.remove()
  • removeIf(...)
Next up: Practice: Word Counter — put module ten together