Find common elements in two ArrayLists in Java

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:

  1. Creating the Lists: We create two ArrayLists named list1 and list2 and populate them with some integers.
  2. Printing the Lists: We print the contents of both list1 and list2 using System.out.println().
  3. Finding Common Elements: We call the findCommonElements() method to find the common elements between list1 and list2.
  4. findCommonElements() Method: This method uses two HashSet instances (set1 and set2) to store the unique elements from each list.
  5. Populating the HashSets: We populate set1 with the elements from list1 and set2 with the elements from list2. This ensures that each set contains only unique elements, effectively removing duplicates from the original lists.
  6. Finding Common Elements: We use the retainAll() method on set1 and pass set2 as an argument. This method modifies set1 to retain only the elements that are also present in set2, which are the common elements.
  7. Converting HashSet to ArrayList: After finding the common elements in the set1, we convert it back to an ArrayList named commonElements to maintain the order.
  8. 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.

Java logical programs list


Java Basic Programs

Java Programs based on the Collection Framework

Leave a Reply

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