List remove Java

next prev

Remove an Element from ArrayList in Java

ArrayList is similar to the array whose size can be modified. The ArrayList class is available in the Java.util package and extends the List interface. Adding and removing an element from the ArrayList is very easy by using its built-in methods add() and remove(). However, there is more than one way of removing an element from the ArrayList that are as follows:

  1. Using ArrayList.remove() Method
    1. By index.
    2. By element
  2. Using Iterator.remove() Method
  3. Using ArrayList.removeIf() Method
List remove Java

All these three ways are best in their own, and can be used in some different scenario. Let's understand all these three ways, one by one.

ArrayList.remove() Method

Using the remove() method of the ArrayList class is the fastest way of deleting or removing the element from the ArrayList. It also provides the two overloaded methods, i.e., remove(int index) and remove(Object obj). The remove(int index) method accepts the index of the object to be removed, and the remove(Object obj) method accepts the object to be removed.

Let's take an example to understand how the remove() method is used.

RemoveMethod.java

Output:

List remove Java

Let's take another example to understand how the remove() method is used to remove the specified element from the ArrayList.

RemoveElementMethod.java

Output:

List remove Java

Iterator.remove() Method

The Iterator.remove() method is another way of removing an element from an ArrayList. It is not so helpful in case when iterating over elements. When we use the remove() method while iterating the elements, it throws the ConcurrentModificationException. The Iterator class removes elements properly while iterating the ArrayList.

Let's take an example to understand how the Iterator.remove() method is used.

IteratorRemoveMethod.java

Output:

List remove Java

ArrayList.removeIf() Method

If we want to remove an element from the ArrayList which satisfy the predicate filter, the removeIf() method is best suited for this case. We pass the predicate filter to that method as an argument.

Let's take an example to understand how the removeIf() method is used.

RemoveIfMethod.java

Output:

List remove Java

All of the above-discussed methods are used for different scenarios. Using ArrayList.remove() method is the fastest way for removing an element from the ArrayList.


Next TopicHow to Create Test Cases for Exceptions in Java


prev next