Learn to remove an item from an ArrayList using the remove() and removeIf() methods. The remove() method removes either the specified element or an element from the specified index. The removeIf() removes all elements matching a Predicate.
1. ArrayList.remove(), removeAll() and removeIf()
The ArrayList.remove() method is overloaded.
E remove(int index) boolean remove(E element))
- The remove(int index) – removes the element at the specified index and returns the removed item.
- remove(E element) – remove the specified element by value and returns true if the element was removed, else returns false.
The removeAll() accepts a collection and removes all elements of the specified collection from the current list.
boolean removeAll(Collection<?> c)
The removeIf() accepts a Predicate to match the elements to remove.
boolean removeIf(Predicate<? super E> filter)
2. Remove an Element by Specified Index
The remove(index) method removes the specified element E
at the specified position in this list. It removes the element currently at that position, and all subsequent elements are moved to the left (will subtract one from their indices).
Note that List Indices start with 0.
ArrayList<String> namesList = new ArrayList<String>(Arrays.asList( "alex", "brian", "charles") );
System.out.println(namesList); //list size is 3
//Remove element at 1 index
namesList.remove(1);
System.out.println(namesList); //list size is 2
Program output.
[alex, brian, charles]
[alex, charles]
2. Remove Specified Element(s) By Value
The remove(Object) method removes the first occurrence of the specified element E
in this list. As this method removes the object, the list size decreases by one.
ArrayList<String> namesList = new ArrayList<>(Arrays.asList( "alex", "brian", "charles", "alex") );
System.out.println(namesList);
namesList.remove("alex");
System.out.println(namesList);
Program output.
[alex, brian, charles, alex]
[brian, charles, alex]
To remove all occurrences of the specified element, we can use the removeAll() method. As this method accepts a collection argument, we first need to wrap the element to remove inside a List.
namesList.removeAll(List.of("alex"));
Program output.
[brian, charles]
3. Remove Element(s) with Matching Condition
We can use another super easy syntax from Java 8 stream to remove all elements for a given element value using the removeIf() method.
The following Java program uses List.removeIf() to remove multiple elements from the arraylist in java by element value.
ArrayList<String> namesList = new ArrayList<String>(Arrays.asList( "alex", "brian", "charles", "alex") );
System.out.println(namesList);
namesList.removeIf( name -> name.equals("alex"));
System.out.println(namesList);
Program output.
[alex, brian, charles, alex]
[brian, charles]
Happy Learning !!
Read More: ArrayList Java Docs