Remove Elements from a List

Java lists offer several ways to delete elements: by position, by value, by condition, by membership in another collection, or by range. They differ in what they remove, what they return, and how much work they do. This page explains each, shows the remove(int) versus remove(Object) trap, removes duplicates, covers lists that cannot change, and measures the bulk methods.

Contents

How removal works in a list

Removing from an ArrayList means closing the gap: every element after the removed one moves one slot to the left, so removing near the start of a long list costs time proportional to its length. A LinkedList only relinks two neighbours, but first has to walk to the element. The bulk methods avoid repeated shifting: ArrayList.removeIf marks the elements to remove in one pass and compacts the array in a second, so removing many elements costs about the same as removing one.

Not every List supports removal. Lists from List.of, Collections.unmodifiableList and stream().toList() reject any change, and Arrays.asList has a fixed size because it is a view of an array.

Ways to remove from a list
MethodSinceRemovesReturns
remove(int index)Java 1.2The element at a positionThe removed element
remove(Object o)Java 1.2The first element equal to otrue if one was found
removeIf(predicate)Java 8Every element matching a conditiontrue if any were removed
removeAll(collection)Java 1.2Every element contained in the other collectiontrue if the list changed
retainAll(collection)Java 1.2Every element not in the other collectiontrue if the list changed
subList(from, to).clear()Java 1.2A range of positionsNothing
removeFirst(), removeLast()Java 21An end elementThe removed element
clear()Java 1.2EverythingNothing

Removal also changes indexes: after removing position 2, the element that was at 3 is now at 2. Code that removes several positions one by one must go from the highest index to the lowest, or use one of the bulk methods. Removing inside a loop needs special care and has its own page, removing elements while iterating. All programs here ran on JDK 21.

Remove by index or by value

The names list has a duplicate, and the second example uses a list of Integer, where an index and a value look the same in source code.

Java
import java.util.ArrayList;
import java.util.List;

public class RemoveBasics {

    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of("ann", "bob", "cy", "bob"));

        String gone = names.remove(0);               // by index, returns the element
        System.out.println("remove(0) -> " + gone + "  " + names);

        boolean found = names.remove("bob");         // by value, first match only
        System.out.println("remove(\"bob\") -> " + found + "  " + names);

        System.out.println("remove(\"zed\") -> " + names.remove("zed"));

        // The Integer trap: remove(int) vs remove(Object)
        List<Integer> nums = new ArrayList<>(List.of(10, 20, 3, 40));
        nums.remove(3);                              // index 3, removes 40
        System.out.println("remove(3):                  " + nums);
        nums.remove(Integer.valueOf(3));             // value 3
        System.out.println("remove(Integer.valueOf(3)): " + nums);
    }
}

Output:

Output
remove(0) -> ann  [bob, cy, bob]
remove("bob") -> true  [cy, bob]
remove("zed") -> false
remove(3):                  [10, 20, 3]
remove(Integer.valueOf(3)): [10, 20]
  • remove(0) returns the removed element, ann. remove("bob") removes only the first bob and returns true; a value that is not there returns false.
  • For a List<Integer>, remove(3) calls remove(int index), because an int argument matches that overload exactly. It removed the element at index 3, not the value 3. remove(Integer.valueOf(3)) calls remove(Object) and removed the value. This is one of the most common Java collection bugs.
  • An index outside the list throws IndexOutOfBoundsException.
  • remove(Object) uses equals to find the element, so it only works for classes with a proper equals. For a class that does not override it, only the same instance is found. Records and the standard value classes such as String and Integer compare by content.

Remove many: removeIf, removeAll, retainAll and ranges

A list of scores with a repeated value shows how each bulk method treats duplicates.

Java
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class RemoveMany {

    public static void main(String[] args) {
        List<Integer> scores = new ArrayList<>(List.of(55, 91, 38, 72, 38, 100, 64));

        // removeIf: every element matching a condition
        List<Integer> passed = new ArrayList<>(scores);
        passed.removeIf(s -> s < 60);
        System.out.println("removeIf < 60:      " + passed);

        // removeAll: every element equal to any element of another collection
        List<Integer> without = new ArrayList<>(scores);
        without.removeAll(Set.of(38, 100));
        System.out.println("removeAll {38,100}: " + without);

        // retainAll: keep only those, remove the rest
        List<Integer> kept = new ArrayList<>(scores);
        kept.retainAll(Set.of(38, 100));
        System.out.println("retainAll {38,100}: " + kept);

        // subList(...).clear(): remove a range of indexes [from, to)
        List<Integer> trimmed = new ArrayList<>(scores);
        trimmed.subList(1, 4).clear();
        System.out.println("subList(1,4).clear: " + trimmed);

        // clear: everything
        trimmed.clear();
        System.out.println("clear:              " + trimmed + " isEmpty=" + trimmed.isEmpty());
    }
}

Output:

Output
removeIf < 60:      [91, 72, 100, 64]
removeAll {38,100}: [55, 91, 72, 64]
retainAll {38,100}: [38, 38, 100]
subList(1,4).clear: [55, 38, 100, 64]
clear:              [] isEmpty=true
  • removeIf(s -> s < 60) removed every score below 60 in one call, both copies of 38 included.
  • removeAll removes every element that the argument contains, all copies of it, not one per entry in the argument. retainAll keeps only those elements, here both 38s and the 100.
  • subList(1, 4).clear() removed positions 1 to 3 in one operation. A sublist is a view, so clearing it changes the original list, and the array is shifted once instead of three times.
  • clear() empties the list but keeps an ArrayList's capacity.
  • All of these return or report whether anything changed, which is useful for logging or for deciding whether to save. removeIf returning false means nothing matched.
  • Java 21 added removeFirst() and removeLast() to every List. On an empty list they throw NoSuchElementException, while remove(0) throws IndexOutOfBoundsException.

Lists that cannot be changed

Removal fails at run time, not at compile time, on several common list types. The program tries it on two of them and shows the fix.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CannotRemove {

    public static void main(String[] args) {
        // List.of: fully immutable
        try {
            List.of(1, 2, 3).remove(0);
        } catch (UnsupportedOperationException e) {
            System.out.println("List.of(...).remove:      UnsupportedOperationException");
        }

        // Arrays.asList: fixed size, so set works but remove does not
        List<Integer> fixed = Arrays.asList(1, 2, 3);
        fixed.set(0, 9);
        try {
            fixed.remove(0);
        } catch (UnsupportedOperationException e) {
            System.out.println("Arrays.asList(...).remove: UnsupportedOperationException");
        }

        // The fix in both cases: copy into an ArrayList first
        List<Integer> copy = new ArrayList<>(fixed);
        copy.remove(0);
        System.out.println("copy after remove:         " + copy);
    }
}

Output:

Output
List.of(...).remove:      UnsupportedOperationException
Arrays.asList(...).remove: UnsupportedOperationException
copy after remove:         [2, 3]
  • List.of(...) is immutable, and remove throws UnsupportedOperationException. The same applies to stream().toList() and Collections.unmodifiableList.
  • Arrays.asList returns a fixed-size view of an array: set works, but add and remove throw.
  • Copying into a new ArrayList gives a list that can be changed freely. See immutable collections for which factory returns what.

Removing duplicates

Tags collected from several sources often repeat. The list below has three copies of java and two of sql, so the order of the result shows which occurrence each method keeps.

Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class Duplicates {

    public static void main(String[] args) {
        List<String> tags = List.of("java", "sql", "java", "go", "sql", "java");

        // Keep the first occurrence of each value, in order
        System.out.println("LinkedHashSet:   " + new ArrayList<>(new LinkedHashSet<>(tags)));
        System.out.println("stream distinct: " + tags.stream().distinct().toList());

        // In place, keeping the first occurrence
        List<String> inPlace = new ArrayList<>(tags);
        Set<String> seen = new HashSet<>();
        inPlace.removeIf(t -> !seen.add(t));
        System.out.println("removeIf + seen: " + inPlace);

        // Keep the LAST occurrence instead: walk backwards
        List<String> last = new ArrayList<>(tags);
        Collections.reverse(last);
        last = new ArrayList<>(new LinkedHashSet<>(last));
        Collections.reverse(last);
        System.out.println("keep last:       " + last);

        // Remove every copy of one value, and remove nulls
        List<String> all = new ArrayList<>(tags);
        all.removeAll(List.of("java"));
        System.out.println("removeAll(java): " + all);
        List<String> withNulls = new ArrayList<>(java.util.Arrays.asList("a", null, "b", null));
        withNulls.removeIf(java.util.Objects::isNull);
        System.out.println("nulls removed:   " + withNulls);
    }
}

Output:

Output
LinkedHashSet:   [java, sql, go]
stream distinct: [java, sql, go]
removeIf + seen: [java, sql, go]
keep last:       [go, sql, java]
removeAll(java): [sql, go, sql]
nulls removed:   [a, b]
  • Copying through a LinkedHashSet and stream().distinct() both keep the first occurrence of each value in the original order. A plain HashSet would lose the order.
  • removeIf(t -> !seen.add(t)) removes duplicates in place: Set.add returns false for a value already seen.
  • To keep the last occurrence instead, reverse, deduplicate and reverse again: go, sql, java.
  • removeAll(List.of("java")) removes every copy of one value, and removeIf(Objects::isNull) removes nulls.

Duplicates decided by a property rather than by equals, such as users with the same email, are handled on the filtering page.

Removing at the ends: ArrayList, LinkedList and ArrayDeque

Where an element sits decides what removing it costs. The program empties a 100,000-element collection one element at a time from the front and from the back, and then removes 2,000 elements from the middle by index, comparing ArrayList, LinkedList and ArrayDeque.

Java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Supplier;

public class EndsAndLinked {

    static final int N = 100_000;

    static <T> long best(Supplier<T> fresh, java.util.function.Consumer<T> drain) {
        long best = Long.MAX_VALUE;
        for (int r = 0; r < 3; r++) {
            T c = fresh.get();
            long start = System.nanoTime();
            drain.accept(c);
            best = Math.min(best, System.nanoTime() - start);
        }
        return best;
    }

    static ArrayList<Integer> arrayList() {
        ArrayList<Integer> l = new ArrayList<>();
        for (int i = 0; i < N; i++) {
            l.add(i);
        }
        return l;
    }

    public static void main(String[] args) {
        System.out.println("remove all 100,000 elements one by one, best of 3:");
        long front = best(EndsAndLinked::arrayList, l -> {
            while (!l.isEmpty()) {
                l.remove(0);                                    // shifts everything left
            }
        });
        long back = best(EndsAndLinked::arrayList, l -> {
            while (!l.isEmpty()) {
                l.removeLast();                                 // nothing to shift
            }
        });
        long linked = best(() -> new LinkedList<>(arrayList()), l -> {
            while (!l.isEmpty()) {
                l.removeFirst();
            }
        });
        long deque = best(() -> new ArrayDeque<>(arrayList()), d -> {
            while (!d.isEmpty()) {
                d.pollFirst();
            }
        });
        System.out.printf("  ArrayList.remove(0)       %8.1f ms%n", front / 1e6);
        System.out.printf("  ArrayList.removeLast()    %8.1f ms%n", back / 1e6);
        System.out.printf("  LinkedList.removeFirst()  %8.1f ms%n", linked / 1e6);
        System.out.printf("  ArrayDeque.pollFirst()    %8.1f ms%n", deque / 1e6);

        // LinkedList removes cheaply only where it already is: remove(index) walks first
        long walk = best(() -> new LinkedList<>(arrayList()), l -> {
            for (int i = 0; i < 2_000; i++) {
                l.remove(l.size() / 2);                         // walk to the middle each time
            }
        });
        long arrayMiddle = best(EndsAndLinked::arrayList, l -> {
            for (int i = 0; i < 2_000; i++) {
                l.remove(l.size() / 2);
            }
        });
        System.out.println("remove 2,000 elements from the middle by index:");
        System.out.printf("  LinkedList                %8.1f ms%n", walk / 1e6);
        System.out.printf("  ArrayList                 %8.1f ms%n", arrayMiddle / 1e6);
        List<Integer> check = arrayList();
        check.subList(0, N / 2).clear();
        System.out.println("check: subList(0, 50,000).clear() leaves " + check.size()
                + ", first " + check.get(0));
    }
}

Output (rough comparison on a 2-CPU Linux VM, JDK 21, best of 3):

Output
remove all 100,000 elements one by one, best of 3:
  ArrayList.remove(0)          503.7 ms
  ArrayList.removeLast()         0.1 ms
  LinkedList.removeFirst()       0.6 ms
  ArrayDeque.pollFirst()         0.1 ms
remove 2,000 elements from the middle by index:
  LinkedList                   138.7 ms
  ArrayList                      6.8 ms
check: subList(0, 50,000).clear() leaves 50000, first 50000
  • ArrayList.remove(0) was by far the slowest: each call shifted all remaining elements one place left, about 5 billion element moves in total. Removing from the end with removeLast() shifts nothing and was over a thousand times faster.
  • LinkedList.removeFirst() and ArrayDeque.pollFirst() both removed from the front in constant time. For a queue that is consumed from the front, use ArrayDeque; it was at least as fast here and uses far less memory per element than a linked node. See queues and deques.
  • In the middle, the picture reversed. LinkedList.remove(index) first walks node by node to the position, and that walk cost much more than ArrayList's fast block shift, so the linked list was many times slower. A linked list only removes cheaply where an iterator already stands.
  • To drop the first half of a list in one step, subList(0, n).clear() shifts the rest once, as the last line confirms.

Capacity and sublist views after removal

Two effects of removal are invisible in the list's contents. An ArrayList keeps its internal array when elements leave, and a sublist taken before a change no longer knows where it stands. The program reads the private array length through reflection, which needs --add-opens java.base/java.util=ALL-UNNAMED, purely to make the capacity visible.

Java
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;

public class SubListAndCapacity {

    // Reads ArrayList's private array length; needs --add-opens java.base/java.util=ALL-UNNAMED
    static int capacity(ArrayList<?> list) throws ReflectiveOperationException {
        Field f = ArrayList.class.getDeclaredField("elementData");
        f.setAccessible(true);
        return ((Object[]) f.get(list)).length;
    }

    public static void main(String[] args) throws Exception {
        // Removing does not give memory back
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < 1_000_000; i++) {
            list.add(i);
        }
        System.out.printf("1,000,000 elements: capacity %,d%n", capacity(list));
        list.removeIf(n -> n >= 10);
        System.out.printf("after removeIf, %d left: capacity %,d%n", list.size(), capacity(list));
        list.clear();
        System.out.printf("after clear():       capacity %,d%n", capacity(list));
        list.add(1);
        list.trimToSize();
        System.out.printf("after trimToSize():  capacity %,d%n", capacity(list));

        // A subList is a view: a structural change to the parent invalidates it
        List<String> names = new ArrayList<>(List.of("ann", "bob", "cid", "dan", "eve"));
        List<String> firstThree = names.subList(0, 3);
        names.remove("eve");                                    // change the parent directly
        try {
            System.out.println(firstThree.size());
        } catch (ConcurrentModificationException e) {
            System.out.println("subList used after the parent changed: "
                    + "ConcurrentModificationException");
        }

        // Removing through the view is fine and updates the parent
        List<String> view = names.subList(0, 3);
        view.remove("bob");
        System.out.println("removed through the view: view " + view + ", list " + names);
    }
}

Output:

Output
1,000,000 elements: capacity 1,215,487
after removeIf, 10 left: capacity 1,215,487
after clear():       capacity 1,215,487
after trimToSize():  capacity 1
subList used after the parent changed: ConcurrentModificationException
removed through the view: view [ann, cid], list [ann, cid, dan]
  • After adding a million elements, the array had room for 1,215,487, because it grows by half each time it fills. Removing all but 10 elements, and even clear(), left that capacity unchanged: about 4.8 MB of references kept alive by an almost empty list. The removed slots are set to null, so the elements themselves can be garbage collected, but the array cannot.
  • trimToSize() shrank the array to the current size, here 1. Call it, or copy the list, when a long-lived list has become much smaller than its peak.
  • A sublist is a view that records the parent's modification count. After names.remove("eve") changed the parent directly, using the old sublist threw ConcurrentModificationException, even though the removed element was outside its range. Take a fresh sublist after changing the parent.
  • Removing through the view is allowed and updates the parent: removing bob from the view also removed it from the list.

How fast is each approach?

The program removes the 50,000 odd numbers from a list of 100,000 three ways, then removes 10,000 values with removeAll, passing them first as a List and then as a HashSet. Each result is the fastest of three runs on a fresh copy.

Java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;

public class RemoveSpeed {

    public static void main(String[] args) {
        int n = 100_000;
        List<Integer> base = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            base.add(i);
        }
        System.out.printf("remove the odd numbers from an ArrayList of %,d%n", n);
        time("removeIf", base, l -> l.removeIf(x -> x % 2 != 0));
        time("iterator.remove", base, l -> {
            for (Iterator<Integer> it = l.iterator(); it.hasNext(); ) {
                if (it.next() % 2 != 0) {
                    it.remove();
                }
            }
        });
        time("filter into a new list", base, l -> {
            List<Integer> keep = new ArrayList<>();
            for (int x : l) {
                if (x % 2 == 0) {
                    keep.add(x);
                }
            }
            l.clear();
            l.addAll(keep);
        });

        List<Integer> unwanted = new ArrayList<>();
        for (int i = 1; i < 20_000; i += 2) {
            unwanted.add(i);
        }
        Set<Integer> unwantedSet = new HashSet<>(unwanted);
        System.out.printf("removeAll of %,d values from the same list%n", unwanted.size());
        time("removeAll(List)", base, l -> l.removeAll(unwanted));
        time("removeAll(HashSet)", base, l -> l.removeAll(unwantedSet));
    }

    // Best of 3 runs, each on a fresh copy
    static void time(String name, List<Integer> base, Consumer<List<Integer>> op) {
        long best = Long.MAX_VALUE;
        int size = 0;
        for (int run = 0; run < 3; run++) {
            List<Integer> copy = new ArrayList<>(base);
            long t0 = System.nanoTime();
            op.accept(copy);
            best = Math.min(best, System.nanoTime() - t0);
            size = copy.size();
        }
        System.out.printf("  %-24s %8.1f ms  (%,d left)%n", name, best / 1e6, size);
    }
}

Output (rough timings on a 2-CPU Linux machine, JDK 21):

Output
remove the odd numbers from an ArrayList of 100,000
  removeIf                      1.3 ms  (50,000 left)
  iterator.remove             209.5 ms  (50,000 left)
  filter into a new list        1.6 ms  (50,000 left)
removeAll of 10,000 values from the same list
  removeAll(List)             515.7 ms  (90,000 left)
  removeAll(HashSet)            7.5 ms  (90,000 left)
  • removeIf and building a filtered list both took about a millisecond, because each touches every element once.
  • Removing the same elements one at a time with iterator.remove() was more than a hundred times slower: each removal shifts the rest of the array, so the total work grows with the square of the size.
  • removeAll calls contains on its argument for every element of the list. With a List argument that is a linear scan each time, 100,000 × 10,000 comparisons; with a HashSet it is a hash lookup, and the call was more than a hundred times faster. Wrap large arguments in a HashSet before calling removeAll or retainAll.

Which method to use

Choosing a removal method
To removeUse
The element at a positionlist.remove(index)
One value from a List<Integer>list.remove(Integer.valueOf(v))
The first occurrence of a valuelist.remove(value)
Everything that matches a conditionlist.removeIf(condition)
Every value that is in another collectionlist.removeAll(new HashSet<>(other))
Everything except some valueslist.retainAll(set)
A range of positionslist.subList(from, to).clear()
Duplicates, keeping ordernew ArrayList<>(new LinkedHashSet<>(list))
From an immutable listCopy into a new ArrayList first, or filter into a new list

Removing from maps is covered on removing entries from a map.