how to find common elements in arraylists java

By | May 18, 2020

You were given two arraylists as below and you have to identify the common elements present in them.

ArrayList1: [sleenium99, automation, tutorials, java]

ArrayList2: [arraylist, sleenium99, automation, tutorials, collections]

Output is: [sleenium99, automation, tutorials]

Method 1:

We are going to achieve this task with the help of retainAll method present in the ArrayList.


list1: [selenium99, automation, tutorials, java]
list2: [arraylist, selenium99, automation, tutorials, collections]
Common elements are: [arraylist, selenium99, automation, tutorials, collections]

Above method modifies the array list ‘list1’ so at the end of the test it contains only common elements. If your requirement is not to modify the existing array list, then you can take the help of third array list. Please look at the code below.

Method 2:


Common elements are: [selenium99, automation, tutorials]
List1: [selenium99, automation, tutorials, java]

Also, we can achieve it by using streams filter.

Method 3:


[selenium99, automation, tutorials]

This article is contributed by Durga Sreenu Rompalli. If you like selenium99 and would like contribute articles, please share your articles at

Please feel free to correct any mistake in the above article by commenting below.

Leave a Reply

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