Remove Common Elements Two Lists Java


It may be required sometimes to remove common elements two lists Java. Following is the code.

ArrayList al1 contains 10, 20 and 30 and ArrayList al2 contains 20, 30, and 50. It is required from al1 to remove 20 and 30 as they are also present in al2. After removal, al1 should print only 10.

import java.util.*;
public class UncommonElements
{
  public static void main(String args[])
  {
     ArrayList al1 = new ArrayList();
     ArrayList al2 = new ArrayList();
     al1.add(10);
     al1.add(20);
     al1.add(30);

     al2.add(20);
     al2.add(30);
     al2.add(50);

     al1.removeAll(al2);

     System.out.println(al1);         // prints only 10
  }
}


Remove Common Elements Two Lists Java
Output screen on Remove Common Elements Two Lists Java

Here we use the removeAll() method of Collection interface. Following is the method signature.

boolean removeAll(Collection col): Removes all the elements in the current collection under manipulation that also exist in the collection passed as parameter. That is, the common elements that exist both in current data structure and the data structure passed as parameter are removed in the current data structure (with which the method is called). Returns true if the operation is successful, else, false.

Another program is available to extract the common elements of two lists using retainAll() method.

Leave a Comment

Your email address will not be published.