Finding common elements between two ArrayList objects is a common operation when comparing collections in Java. The common elements are those values that are present in both lists.
- retainAll()Â is a simple way to keep only the elements common to two lists.
- The Stream API can filter elements from one list based on their presence in another list.
- A loop with contains() provides a simple approach without using advanced APIs.
Examples:
Input: List1 = ["Hii", "Geeks", "Akshat", "Geeks"], List2 = ["Hii", "Akshat", "Java"]
Output: [Hii, Akshat]Input: List1 = ["Hii", "Akshat", "Geeks", "Java", "Python", "SQL"], List2 = ["Geeks", "Java", "Akshat", "HTML", "CSS", "Hii"]
Output: [Hii, Akshat, Geeks, Java]
Methods to Find Common Elements in Two ArrayLists
1. Using retainAll() Method
The retainAll() method is provided by the Collection interface. It removes all elements from the current collection that are not present in the specified collection.
Syntax:
list1.retainAll(list2);
Approach
- Create two ArrayList objects.
- Add elements to both lists.
- Create a copy of the first list if the original list should not be modified.
- Call retainAll() on the copied list.
- The resulting list contains the common elements.
- Print the result.
import java.util.ArrayList;
public class CommonElements{
public static void main(String[] args)
{
// Create first ArrayList
ArrayList<String> list1 = new ArrayList<>();
list1.add("Apple");
list1.add("Mango");
list1.add("Orange");
list1.add("Mango");
// Create second ArrayList
ArrayList<String> list2 = new ArrayList<>();
list2.add("Mango");
list2.add("Banana");
list2.add("Apple");
System.out.println("List1: " + list1);
System.out.println("List2: " + list2);
// Create a copy of list1
ArrayList<String> common = new ArrayList<>(list1);
// Keep only common elements
common.retainAll(list2);
System.out.println("Common elements: " + common);
}
}
Output
List1: [Apple, Mango, Orange, Mango] List2: [Mango, Banana, Apple] Common elements: [Apple, Mango, Mango]
Explanation: The above program finds the common elements between two ArrayLists using the retainAll() method. A copy of list1 is created, and retainAll(list2) removes all elements that are not present in list2, leaving only the common elements in the common list.
2. Using Stream API
The Java Stream API provides another convenient way to find common elements. We can convert the first list into a stream and use the filter() method to keep only those elements that are present in the second list.
Syntax:
list1.stream().filter(list2::contains).collect(Collectors.toList());
The filter() method checks each element of list1. If list2.contains(element) returns true, that element is included in the result.
Approach:
- Create two
ArrayListobjects. - Add elements to both lists.
- Convert the first list into a stream using
stream(). - Use
filter()to check whether each element exists in the second list. - Collect the filtered elements into a new list.
- Print the resulting list.
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class CommonElements {
public static void main(String[] args)
{
ArrayList<Integer> list1 = new ArrayList<>();
list1.add(10);
list1.add(20);
list1.add(30);
list1.add(20);
list1.add(40);
ArrayList<Integer> list2 = new ArrayList<>();
list2.add(20);
list2.add(40);
list2.add(50);
System.out.println("List1: " + list1);
System.out.println("List2: " + list2);
List<Integer> common
= list1.stream()
.filter(list2::contains)
.collect(Collectors.toList());
System.out.println("Common elements: " + common);
}
}
Output
List1: [10, 20, 30, 20, 40] List2: [20, 40, 50] Common elements: [20, 20, 40]
Explanation: The above program uses the Stream API to find common elements by filtering list1 and checking whether each element is present in list2 using contains(). The matching elements are collected into a new list using Collectors.toList() duplicate elements from list1 are retained.
3. Using Loop and contains() Method
The common elements can also be found using a simple for-each loop. This is a straightforward approach and is useful for understanding the basic logic without using retainAll() or streams.
Approach
- Create two ArrayList objects.
- Create a third list to store the common elements.
- Traverse the first list using a loop.
- For each element, use contains() to check whether it exists in the second list.
- If the element exists, add it to the third list.
- Print the common elements.
import java.util.ArrayList;
public class CommonElements{
public static void main(String[] args)
{
ArrayList<String> list1 = new ArrayList<>();
list1.add("Red");
list1.add("Blue");
list1.add("Green");
list1.add("Blue");
ArrayList<String> list2 = new ArrayList<>();
list2.add("Blue");
list2.add("Yellow");
list2.add("Red");
ArrayList<String> common = new ArrayList<>();
System.out.println("List1: " + list1);
System.out.println("List2: " + list2);
// Traverse list1
for (String element : list1){
// Check whether element exists in list2
if (list2.contains(element)) {
common.add(element);
}
}
System.out.println("Common elements: " + common);
}
}
Output
List1: [Red, Blue, Green, Blue] List2: [Blue, Yellow, Red] Common elements: [Red, Blue, Blue]
Explanation: The above program finds common elements by traversing list1 and using contains() to check whether each element is present in list2. If an element exists in both lists, it is added to the common list, and duplicate elements from list1 are retained.