Remove Elements from ArrayList in Java



The method java.util.ArrayList.removeAll() removes all the the elements from the ArrayList that are available in another collection. This method has a single parameter i.e. the Collection whose elements are to be removed from the ArrayList.

A program that demonstrates this is given as follows

Example

 Live Demo

import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String args[]) throws Exception {
      List aList1 = new ArrayList();
      aList1.add("Anna");
      aList1.add("John");
      aList1.add("Mary");
      aList1.add("Amy");
      aList1.add("Harry");
      List aList2 = new ArrayList();
      aList2.add("John");
      aList2.add("Harry");
      aList2.add("Amy");
      aList1.removeAll(aList2);
      System.out.println("The elements in ArrayList aList1 are: " + aList1);
   }
}

The output of the above program is as follows

The elements in ArrayList aList1 are: [Anna, Mary]

Now let us understand the above program.

The ArrayLists aList1 and aList2 are created. Then ArrayList.add() is used to add the elements to both the ArrayList. A code snippet which demonstrates this is as follows

List aList1 = new ArrayList();
aList1.add("Anna");
aList1.add("John");
aList1.add("Mary");
aList1.add("Amy");
aList1.add("Harry");
List aList2 = new ArrayList();
aList2.add("John");
aList2.add("Harry");
aList2.add("Amy");

The ArrayList.removeAll() method is used to remove all the the elements from the aList1 that are available in aList2. Then the elements in aList1 are printed. A code snippet which demonstrates this is as follows

aList1.removeAll(aList2);
System.out.println("The elements in ArrayList aList1 are: " + aList1);
Updated on: 2019-07-30T22:30:24+05:30

140 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements