List Extract Common Elements Java

It may be required sometimes to extract the common elements of two lists in Java. Given in simple terms in this tutorial List Extract Common Elements Java.
Following code on List Extract Common Elements Java illustrates.
import java.util.*;
public class CommonElements
{
  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);

// Now our aim is to create another ArrayList al3, with the common elements 
// of 20 and 30

     ArrayList al3 = new ArrayList(al2);

     al3.retainAll(al1);

     System.out.println(al3);        // prints 20 and 30
  }
}


List Extract Common Elements Java
Output screenshot on List Extract Common Elements Java

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

boolean retainAll(Collection col): Keeps only those elements in the current data structure that also exist in the data structure passed as parameter. Other way to say, removes all the elements in the current data structure that do not exist in the collection col, passed as parameter. Returns true if the operation is successful, else, false.

One more program is available where common elements of two lists are removed.

Leave a Comment

Your email address will not be published.