Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to remove an element from a list

Short answer

remove() removes an element by value or by index:

void main() {
    var colors = new ArrayList<>(List.of("red", "green", "blue"));
    colors.remove("green");
    colors.remove(0);
 
    IO.println(colors);
}

Output:

[blue]

By a condition

removeIf() removes every element for which the condition is true:

void main() {
    var numbers = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
    numbers.removeIf(n -> n % 2 == 0);
 
    IO.println(numbers);
}

Output:

[1, 3, 5]

Several values

removeAll() removes every element that is present in another collection:

void main() {
    var tags = new ArrayList<>(List.of("java", "spam", "sql", "ads"));
    tags.removeAll(Set.of("spam", "ads"));
 
    IO.println(tags);
}

Output:

[java, sql]

A list of numbers

On a List<Integer>, remove(1) removes the element at index 1, not the number 1. To remove the value, pass an object:

void main() {
    var numbers = new ArrayList<>(List.of(5, 1, 7));
 
    numbers.remove(Integer.valueOf(1));
    IO.println(numbers);
 
    numbers.remove(1);
    IO.println(numbers);
}

Output:

[5, 7]
[5]

Common mistake

Removing elements in a for-each loop. The list changes during iteration, and Java throws an exception:

void main() {
    var names = new ArrayList<>(List.of("Anna", "", "Oleg", ""));
    for (String name : names) {
        if (name.isEmpty()) {
            names.remove(name);
        }
    }
}

Output:

Exception in thread "main" java.util.ConcurrentModificationException

Use removeIf() or an explicit Iterator with iterator.remove().

Functions used in this recipe

  • List.remove() — Removes a list element by index or by value.
  • Collection.removeIf() — Removes all collection elements that match a condition.
  • Iterator — An object that hands out collection elements one by one.

Thanks for reading!

Donate to the site — we work hard for you.