Problem Statement: Write a Java program to find the common elements in two ArrayLists.
Here’s a Java program that demonstrates how to find common elements in two ArrayLists
.
package com.javacodepoint.collection;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class FindCommonElementsInArrayListsDemo {
public static void main(String[] args) {
List<Integer> list1 = new ArrayList<>();
list1.add(10);
list1.add(20);
list1.add(30);
list1.add(40);
List<Integer> list2 = new ArrayList<>();
list2.add(20);
list2.add(40);
list2.add(60);
list2.add(80);
System.out.println("List 1: " + list1);
System.out.println("List 2: " + list2);
// Finding common elements
List<Integer> commonElements = findCommonElements(list1, list2);
System.out.println("Common Elements: " + commonElements);
}
// Method to find common elements in two ArrayLists
public static <T> List<T> findCommonElements(List<T> list1, List<T> list2) {
HashSet<T> set1 = new HashSet<>(list1);
HashSet<T> set2 = new HashSet<>(list2);
set1.retainAll(set2);
return new ArrayList<>(set1);
}
}
OUTPUT:
List 1: [10, 20, 30, 40]
List 2: [20, 40, 60, 80]
Common Elements: [20, 40]
Explanation:
- Creating the Lists: We create two
ArrayLists
namedlist1
andlist2
and populate them with some integers. - Printing the Lists: We print the contents of both
list1
andlist2
usingSystem.out.println()
. - Finding Common Elements: We call the
findCommonElements()
method to find the common elements betweenlist1
andlist2
. findCommonElements()
Method: This method uses twoHashSet
instances (set1
andset2
) to store the unique elements from each list.- Populating the HashSets: We populate
set1
with the elements fromlist1
andset2
with the elements fromlist2
. This ensures that each set contains only unique elements, effectively removing duplicates from the original lists. - Finding Common Elements: We use the
retainAll()
method onset1
and passset2
as an argument. This method modifiesset1
to retain only the elements that are also present inset2
, which are the common elements. - Converting HashSet to ArrayList: After finding the common elements in the
set1
, we convert it back to anArrayList
namedcommonElements
to maintain the order. - Returning the Result: The method returns the
commonElements
list, which contains the common elements found in both input lists.
By using HashSet
to store unique elements and take advantage of its retainAll()
method, the program effectively finds and retains the common elements between the two input ArrayLists
.
See also: Convert an ArrayList of strings into a string array.