The java.util.ArrayList class is part of the Collections Framework and is a data structure that allows you to store elements in a format similar to an array, but dynamically. Unlike traditional arrays, the size of an ArrayList can be modified at runtime as elements are added or removed. This feature of the ArrayList will make your task easier if you are working on programs that make extensive use of list manipulation. In this article we explain three ways to remove an element from an ArrayList in Java:
- Remove an element by index using the remove(int) method.
- Remove an element by value using the remove(Object) method.
- Remove an element conditionally.
How to remove element from a Java ArrayList using index?
Removing an element from an ArrayList using its index is one of the most common operations in Java. This approach is useful when you know the exact position of the element within the list. For this, the remove(int index) method is used, which removes the element at the position indicated by the index.
How does remove(int index) work?
The remove(int index) method takes one parameter which is the index of the element you want to remove. The index is zero-based, meaning the first element has index 0, the second has index 1, and so on.
Code example to remove an element by its index:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Crear un ArrayList con elementos
ArrayList<String> lista = new ArrayList<>();
lista.add("Manzana");
lista.add("Plátano");
lista.add("Cereza");
lista.add("Pera");
// Delete the element at index 2 (Cereza)
lista.remove(2);
// Display list content after deletion
System.out.println(lista); // Output: [Manzana, Plátano, Pera]
}
}
In this example, the element at index 2, “Cereza”, is removed from the list. After the operation, the ArrayList contains only the elements “Manzana”, “Plátano”, and “Pera”.
Considerations:
Out of range indexes: If you try to remove an item with an index that does not exist in the list, Java will throw an IndexOutOfBoundsException. Therefore, it is important to ensure that the index is within the range of the list.
// Attempting to drop an index that does not exist
lista.remove(10); // It will throw IndexOutOfBoundsException if the list has less than 11 elements.
How to remove element from a Java ArrayList by value?
In Java, in addition to removing an element from an ArrayList using its index, it is also common to remove elements by value. To do this, the remove(Object o)
method is used, which removes the first occurrence of the object that matches the provided value.
How does remove(Object o) work?
The remove(Object o) method takes an object as an argument and removes it from the list if an exact match is found. If the ArrayList contains more than one instance of the same value, only the first one found is removed. If the value does not exist in the list, the ArrayList remains unchanged and the method returns false.
Code example to delete a specific value:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Create an ArrayList with elements
ArrayList<String> lista = new ArrayList<>();
lista.add("Manzana");
lista.add("Plátano");
lista.add("Cereza");
lista.add("Plátano");
// Remove the value "Plátano" from the list
lista.remove("Plátano");
// Display list content after deletion
System.out.println(lista); // Salida: [Manzana, Cereza, Plátano]
}
}
In this example, the value “Plátano” is removed from the list. Since there are two items with the value “Plátano”, only the first occurrence is removed. The resulting list contains “Manzana”, “Cereza”, and the last “Plátano”.
Considerations for searching for items:
- Exact Match: The
remove(Object o)
method uses the Object‘sequals()
method to determine if an item in the list matches the value you provide. Therefore, it is important that objects are properly comparable. For example, if you are working with custom objects, be sure to override theequals()
method in the object’s class if you need an exact comparison. - Duplicate elements: If the value to be removed appears multiple times in the ArrayList,
remove(Object o)
will remove only the first instance. If you need to remove all occurrences of a value, you can use a loop or a method likeremoveIf()
to do this efficiently.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Create an ArrayList with elements
ArrayList<String> lista = new ArrayList<>();
lista.add("Manzana");
lista.add("Plátano");
lista.add("Cereza");
lista.add("Plátano");
// Remove all occurrences of "Plátano"
lista.removeIf(item -> item.equals("Plátano"));
// Display list content after deletion
System.out.println(lista); // Salida: [Manzana, Cereza]
}
}
How to remove element from a Java ArrayList that meets a specific condition?
There are several ways to remove an element from an ArrayList in Java based on a condition. Let’s first see what happens if we do it while iterating the list using a for loop. For this we are going to create a list of Strings and, for illustrative purposes, we are going to try to remove the elements whose length is greater than three characters:
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> animals = new ArrayList<>(Arrays.asList("Dog", "Cat", "Bird"));
for (String animal : animals){
if (animal.length() > 3){
animals.remove(animal);
}
}
}
}
In the example above, we used a Java for loop to iterate through a collection and then evaluate each item to see if it meets our criteria. If so, we attempt to remove that item. However, in doing so, we encounter a ConcurrentModificationException:
Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1095)
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:1049)
at Main.main(Main.java:8)
This happens because the ArrayList detects that its structure has been modified while being traversed with an implicit loop iterator, which violates Java’s concurrency rules.
What we’re going to do is look at a couple of different ways to solve this. One of them is the traditional way and the other is a newer method that was added to Java 8 in the Collection interface.
Solution 1 (traditional)
One way to solve this is to go the old school way, the way we used to before Java 8. We can create the iterator explicitly and loop through it directly. So, we’ll create an iterator and loop through it inside a while loop. Then, we’ll check if the element meets our length criterion, and if not, we’ll use the iterator to remove it using the remove() method:
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> animals = new ArrayList<>(Arrays.asList("Dog", "Cat", "Bird"));
Iterator<String> iterator = animals.iterator();
String animal = null;
while(iterator.hasNext()){
animal = iterator.next();
if (animal.length() > 3){
iterator.remove();
}
}
System.out.println(animals);
}
}
OUTPUT:
[Dog, Cat]
Solution 2 (Java 8)
The solution seen above, although effective, is an archaic and verbose way of doing it. Fortunately, Java 8 introduced a new method in the Collection interface called removeIf()
. This method takes a predicate, allowing us to remove elements based on some condition.
How does removeIf() work?
The removeIf()
method takes a predicate as an argument. A predicate is an expression that evaluates a condition on each element in the ArrayList. If the element meets that condition, it will be removed from the list. This is a way to perform removals in a more flexible way than relying only on indexes or exact values.
Example 1: Remove elements greater than 10:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Create an ArrayList with elements
ArrayList<Integer> lista = new ArrayList<>();
lista.add(5);
lista.add(12);
lista.add(8);
lista.add(15);
lista.add(3);
// Remove all items greater than 10
lista.removeIf(n -> n > 10);
// Display list content after deletion
System.out.println(lista); // Output: [5, 8, 3]
}
}
In this example, the lambda expression n -> n > 10
is used as a predicate to remove all elements that are greater than 10. After execution, elements 12 and 15 are removed from the list.
Example 2: Remove strings that do not contain a specific substring:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Create an ArrayList with strings
ArrayList<String> lista = new ArrayList<>();
lista.add("manzana");
lista.add("plátano");
lista.add("cereza");
lista.add("pera");
// Remove all strings that do not contain the letter 'z'
lista.removeIf(s -> !s.contains("z"));
// Display list content after deletion
System.out.println(lista); // Output: [manzana, cereza]
}
}
Conclusion
In this article we have seen different ways to remove an element from an ArrayList in Java. We started with the basic methods like remove(int)
to remove by index and remove(Object)
to remove by value. Then, we tackle more complex situations such as conditional removal, where we present classical solutions using an explicit iterator and the modern alternative with the removeIf()
method introduced in Java 8.
If you need more details about handling collections in Java, we recommend exploring more about iterators, the use of other collections such as HashSet or LinkedList, and how to take advantage of advanced language features such as Streams and Lambdas. To go deeper, check out our other related articles and practical tutorials on the topic.