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.
public class CommonElements
public static void main(String args)
ArrayList<Integer> al1 = new ArrayList<Integer>();
ArrayList<Integer> al2 = new ArrayList<Integer>();
// Now our aim is to create another ArrayList al3, with the common elements
// of 20 and 30
ArrayList<Integer> al3 = new ArrayList<Integer>(al2);
System.out.println(al3); // prints 20 and 30
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.