1. Overview
In this tutorial, we're going to see how to remove elements from an ArrayList in Java using different techniques. Given a list of sports, let's see how we can get rid of some elements of the following list:
List<String> sports = new ArrayList<>(); sports.add("Football"); sports.add("Basketball"); sports.add("Baseball"); sports.add("Boxing"); sports.add("Cycling");
2. ArrayList#remove
ArrayList has two available methods to remove an element, passing the index of the element to be removed, or passing the element itself to be removed, if present. We're going to see both usages.
2.1. Remove by Index
Using remove passing an index as parameter, we can remove the element at the specified position in the list and shift any subsequent elements to the left, subtracting one from their indices. After execution, remove method will return the element that has been removed:
sports.remove(1); // since index starts at 0, this will remove "Basketball" assertEquals(4, sports.size()); assertNotEquals(sports.get(1), "Basketball");
2.2. Remove by Element
Another way is to remove the first occurrence of an element from a list using this method. Formally speaking, we're removing the element with the lowest index if exists, if not, the list is unchanged:
sports.remove("Baseball"); assertEquals(4, sports.size()); assertFalse(sports.contains("Baseball"));
3. Removing While Iterating
Sometimes we want to remove an element from an ArrayList while we're looping it. Due to not generate a ConcurrentModificationException, we need to use Iterator class to do it properly.
Let's see how we can get rid of an element in a loop:
Iterator<String> iterator = sports.iterator(); while (iterator.hasNext()) { if (iterator.next().equals("Boxing")) { iterator.remove(); } }
4. ArrayList#removeIf (JDK 8+)
If we're using JDK 8 or higher versions, we can take advantage of ArrayList#removeIf which removes all of the elements of the ArrayList that satisfy a given predicate.
sports.removeIf(p -> p.equals("Cycling")); assertEquals(4, sports.size()); assertFalse(sports.contains("Cycling"));
Finally, we can do it using third party libraries like Apache Commons and, if we want to go deeper, we can see how to remove all specific occurrences in an efficient way.
5. Conclusion
In this tutorial, we looked at the various ways of removing elements from an ArrayList in Java.
As usual, all the examples used at this tutorial are available on GitHub.