Remove Common Elements in Two Lists Java


It may be required sometimes to remove the elements from a list which also exist in another list in Java coding. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.util.*;
public class UncommonElements
{
  public static void main(String args[])
  {
     ArrayList<Integer> al1 = new ArrayList<Integer>();
     ArrayList<Integer> al2 = new ArrayList<Integer>();
     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
  }
}

Output screen of UncommonElements.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 Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>