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 Remove by index or by value Remove many: removeIf, removeAll, retainAll and ranges Lists that cannot be changed Removing duplicates Removing at the ends: ArrayList, LinkedList and ArrayDeque Capacity and sublist views after removal How fast is each approach? Which method to use
How removal works in a list
Removing from an ArrayListLinkedListArrayList.removeIf
Not every ListList.ofCollections.unmodifiableListstream().toList()Arrays.asList
| Method | Since | Removes | Returns |
|---|---|---|---|
remove(int index) | Java 1.2 | The element at a position | The removed element |
remove(Object o) | Java 1.2 | The first element equal to o | true |
removeIf(predicate) | Java 8 | Every element matching a condition | true |
removeAll(collection) | Java 1.2 | Every element contained in the other collection | true |
retainAll(collection) | Java 1.2 | Every element not in the other collection | true |
subList(from, to).clear() | Java 1.2 | A range of positions | Nothing |
removeFirst()removeLast() | Java 21 | An end element | The removed element |
clear() | Java 1.2 | Everything | Nothing |
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,
Remove by index or by value
The names list has a duplicate, and the second example uses a list of Integer
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:
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]
returns the removed element,remove(0) .ann removes only the firstremove("bob") and returnsbob ; a value that is not there returnstrue .false- For a
,List<Integer> callsremove(3) , because anremove(int index) argument matches that overload exactly. It removed the element at index 3, not the value 3.int callsremove(Integer.valueOf(3)) and removed the value. This is one of the most common Java collection bugs.remove(Object) - An index outside the list throws
.IndexOutOfBoundsException usesremove(Object) to find the element, so it only works for classes with a properequals . For a class that does not override it, only the same instance is found. Records and the standard value classes such asequals andString compare by content.Integer
Remove many: removeIf, removeAll, retainAll and ranges
A list of scores with a repeated value shows how each bulk method treats duplicates.
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:
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
removed every score below 60 in one call, both copies of 38 included.removeIf(s -> s < 60) removes every element that the argument contains, all copies of it, not one per entry in the argument.removeAll keeps only those elements, here both 38s and the 100.retainAll 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.subList(1, 4).clear() empties the list but keeps anclear() 's capacity.ArrayList- All of these return or report whether anything changed, which is useful for logging or for deciding whether to save.
returningremoveIf means nothing matched.false - Java 21 added
andremoveFirst() to everyremoveLast() . On an empty list they throwList , whileNoSuchElementException throwsremove(0) .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.
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:
List.of(...).remove: UnsupportedOperationException
Arrays.asList(...).remove: UnsupportedOperationException
copy after remove: [2, 3]
is immutable, andList.of(...) throwsremove . The same applies toUnsupportedOperationException andstream().toList() .Collections.unmodifiableList returns a fixed-size view of an array:Arrays.asList works, butset andadd throw.remove- Copying into a new
gives a list that can be changed freely. SeeArrayListimmutable collections for which factory returns what.
Removing duplicates
Tags collected from several sources often repeat. The list below has three copies of javasql
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:
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
andLinkedHashSet both keep the first occurrence of each value in the original order. A plainstream().distinct() would lose the order.HashSet removes duplicates in place:removeIf(t -> !seen.add(t)) returnsSet.add for a value already seen.false- To keep the last occurrence instead, reverse, deduplicate and reverse again:
.go, sql, java removes every copy of one value, andremoveAll(List.of("java")) removes nulls.removeIf(Objects::isNull)
Duplicates decided by a property rather than by equals
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 ArrayListLinkedListArrayDeque
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):
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
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 withArrayList.remove(0) shifts nothing and was over a thousand times faster.removeLast() andLinkedList.removeFirst() both removed from the front in constant time. For a queue that is consumed from the front, useArrayDeque.pollFirst() ; it was at least as fast here and uses far less memory per element than a linked node. SeeArrayDequequeues and deques .- In the middle, the picture reversed.
first walks node by node to the position, and that walk cost much more thanLinkedList.remove(index) 's fast block shift, so the linked list was many times slower. A linked list only removes cheaply where an iterator already stands.ArrayList - To drop the first half of a list in one step,
shifts the rest once, as the last line confirms.subList(0, n).clear()
Capacity and sublist views after removal
Two effects of removal are invisible in the list's contents. An ArrayList--add-opens java.base/java.util=ALL-UNNAMED
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:
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
, left that capacity unchanged: about 4.8 MB of references kept alive by an almost empty list. The removed slots are set toclear() , so the elements themselves can be garbage collected, but the array cannot.null 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.trimToSize()- A sublist is a view that records the parent's modification count. After
changed the parent directly, using the old sublist threwnames.remove("eve") , even though the removed element was outside its range. Take a fresh sublist after changing the parent.ConcurrentModificationException - Removing through the view is allowed and updates the parent: removing
from the view also removed it from the list.bob
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 removeAllListHashSet
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):
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)
and building a filtered list both took about a millisecond, because each touches every element once.removeIf- Removing the same elements one at a time with
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.iterator.remove() callsremoveAll on its argument for every element of the list. With acontains argument that is a linear scan each time, 100,000 × 10,000 comparisons; with aList it is a hash lookup, and the call was more than a hundred times faster. Wrap large arguments in aHashSet before callingHashSet orremoveAll .retainAll
Which method to use
| To remove | Use |
|---|---|
| The element at a position | list.remove(index) |
One value from a List<Integer> | list.remove(Integer.valueOf(v)) |
| The first occurrence of a value | list.remove(value) |
| Everything that matches a condition | list.removeIf(condition) |
| Every value that is in another collection | list.removeAll(new HashSet<>(other)) |
| Everything except some values | list.retainAll(set) |
| A range of positions | list.subList(from, to).clear() |
| Duplicates, keeping order | new ArrayList<>(new LinkedHashSet<>(list)) |
| From an immutable list | Copy into a new ArrayList |
Removing from maps is covered on