In this tutorial we will learn how to get the common elements between two ArrayList. We would be using removeAll() method to retain only the common elements between two lists.
public boolean removeAll(Collection<?> c)
It removes all the elements in the list that are not contained in the specified list.
Find Common Elements Example
public class FindCommonElements { public static void main(String args[]) { List list1 = new ArrayList(); list1.add(1); list1.add(3); list1.add(6); list1.add(7); list1.add(9); List list2 = new ArrayList(); list2.add(2); list2.add(5); list2.add(6); list2.add(1); //Get the common elements between list1 and list2 list2.retainAll(list1); System.out.println("Common Elements are : "+list2); } }
Output :
Common Elements are : [2, 5]
Leave a Reply