June 21, 2022

How to Remove Elements From Java ArrayList

If you need to remove or delete an element from ArrayList in Java, you have 3 options.

  1. Using the remove() method of the ArrayList class to remove element. See example.
  2. Using the remove() method of the iterator returned by ArrayList. See example.
  3. Using the removeIf() method Java 8 onward. See example.

Removing element using ArrayList’s remove method

There are two variants of the remove() method in the ArrayList class-

  • remove(int index)- This method removes the element at the specified index in this list.
  • boolean remove(Object o)- This method removes the first occurrence of the specified element from this list, if it is present.

Here is an example to remove element from ArrayList in Java by passing the element itself (using remove(Object o) method).

import java.util.List;
public class ListElementRemoval {
  public static void main(String[] args) {
    List<String> carList = new ArrayList<String>();
    carList.add("Audi");
    carList.add("BMW");
    carList.add("Jaguar");
    carList.add("BMW");
    carList.add("Mini Cooper");
    
    System.out.println("List elements- " + carList);
    // removing element
    carList.remove("Mini Cooper");        
    System.out.println("List elements after removal- " + carList);
  }
}
Output
List elements- [Audi, BMW, Jaguar, BMW, Mini Cooper]
List elements after removal- [Audi, BMW, Jaguar, BMW]

Removing element using iterator’s remove method

If you want to remove an element from ArrayList while iterating the ArrayList then you should use remove() method of the Iterator itself. It is required because it is not permitted to structurally modify (add or remove elements) ArrayList at any time after the iterator is created except through the iterator's own remove method not doing so will result in ConcurrentModificationException being thrown.

Let us see it by an example, here element is removed while iterating the List using remove method of the ArrayList class.

import java.util.Iterator;
import java.util.List;

public class ListElementRemoval {
  public static void main(String[] args) {
    List<String> carList = new ArrayList<String>();
    carList.add("Audi");
    carList.add("BMW");
    carList.add("Jaguar");
    carList.add("BMW");
    carList.add("Mini Cooper");    
    // getting iterator
    Iterator<String> itr = carList.iterator();
    while(itr.hasNext()){
      String car = itr.next();
      if(car.equals("Mini Cooper")) {
        // Using ArrayList's remove method
        carList.remove(car);
      }
    }
  }
}
Output
Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:937)
	at java.base/java.util.ArrayList$Itr.next(ArrayList.java:891)
	at com.knpcode.ListElementRemoval.main(ListElementRemoval.java:19)

Here is the changed code where iterator’s remove method is used to remove element from ArrayList.

public class ListElementRemoval {
  public static void main(String[] args) {
    List<String> carList = new ArrayList<String>();
    carList.add("Audi");
    carList.add("BMW");
    carList.add("Jaguar");
    carList.add("BMW");
    carList.add("Mini Cooper");    
    System.out.println("List elements- " + carList);
    // getting iterator
    Iterator<String> itr = carList.iterator();
    while(itr.hasNext()){
      String car = itr.next();
      if(car.equals("Mini Cooper")) {
        itr.remove();
      }
    }
    System.out.println("List elements after removal- " + carList);
  }
}
Output
List elements- [Audi, BMW, Jaguar, BMW, Mini Cooper]
List elements after removal- [Audi, BMW, Jaguar, BMW]

As you can see ConcurrentModificationException is not thrown now.

Removing element using removeIf method

Java 8 onward you can also use removeIf() method to remove element from ArrayList which takes a Predicate as an argument and removes all elements that satisfy the given Predicate.

Predicate is a functional interface added in Java 8.
public class ListElementRemoval {
  public static void main(String[] args) {
    List<String> carList = new ArrayList<String>();
    carList.add("Audi");
    carList.add("BMW");
    carList.add("Jaguar");
    carList.add("BMW");
    carList.add("Mini Cooper");    
    System.out.println("List elements- " + carList);
    
    carList.removeIf(c -> c.equalsIgnoreCase("Mini Cooper"));
    
    System.out.println("List elements after removal- " + carList);
  }
}

Autoboxing issue with remove() method

Since remove() method in ArrayList is overloaded having variants where you can either pass index or object to remove. These overloaded methods may cause problem if element is wrapped to its corresponding wrapper class because of autoboxing.

Let’s try to clarify it with an example where you have an ArrayList of Integers.

public class ListElementRemoval {
  public static void main(String[] args) {
    List<String> carList = new ArrayList<String>();
    carList.add("Audi");
    carList.add("BMW");
    carList.add("Jaguar");
    carList.add("BMW");
    carList.add("Mini Cooper");    
    System.out.println("List elements- " + carList);
    
    carList.removeIf(c -> c.equalsIgnoreCase("Mini Cooper"));
    
    System.out.println("List elements after removal- " + carList);
  }
}

Here you are passing Integer object 6 to be removed from the ArrayList, but the remove() method with int parameter as argument will be used. No autoboxing will happen in this case and you will get an error.

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 6 out-of-bounds for length 4
	at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
	at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
	at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
	at java.base/java.util.Objects.checkIndex(Objects.java:372)
	at java.base/java.util.ArrayList.remove(ArrayList.java:517)
	at com.knpcode.ListElementRemoval.main(ListElementRemoval.java:16)

If there is such ambiguity you should pass object itself for removal.

public static void main(String[] args) {
    List<Integer> numebrList = new ArrayList<Integer>();
    numebrList.add(3);
    numebrList.add(4);
    numebrList.add(5);
    numebrList.add(6);
    System.out.println("List elements- " + numebrList);
    // Passing object explicitly 
    numebrList.remove(Integer.valueOf(6));

    System.out.println("List elements after removal- " + numebrList);
  }
}

That's all for the topic How to Remove Elements From Java ArrayList. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment