Removing While Looping: Iterator

The for-each removal crash

Changing a list while a for-each loop is walking through it makes Java stop with an error:

import java.util.ArrayList;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> nums = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6));
        for (Integer n : nums) {
            if (n % 2 == 0) {
                nums.remove(n);
            }
        }
    }
}

Output (Java stops with an error)

Exception in thread "main" java.util.ConcurrentModificationException

Using an Iterator

An Iterator walks through a collection one item at a time and can safely remove the current item:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> nums = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6));
        Iterator<Integer> it = nums.iterator();
        while (it.hasNext()) {
            int n = it.next();
            if (n % 2 == 0) {
                it.remove();
            }
        }
        System.out.println(nums);
    }
}

Output

[1, 3, 5]

The one-line way: removeIf

import java.util.ArrayList;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> nums = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6));
        nums.removeIf(n -> n % 2 == 0);
        System.out.println(nums);
    }
}

Output

[1, 3, 5]
HOME LABS COMMUNITY DASHBOARD