Java Program to Find Common Elements Between Two Arrays


We can use different approaches in Java to Find Common Elements between two arrays. We will discuss the approaches, including the basic steps involved, and provide the necessary code to achieve our goal. Whether you are a beginner or an experienced Java programmer, this article will provide you with the tools and knowledge necessary to solve this common programming problem. In this article, we will learn different ways of finding the common elements between two arrays.

Examples for Common Elements Between Two Arrays:

Example 1:

Input:  array1 = {4, 2, 3, 1, 6}
array2 = {6, 7, 9, 8, 4}
Output: Common Elements: {2, 6}

In the above example, as array1 and array2 both arrays have common elements 2 and 6. So, the output array for the above example is {2, 6 }

Example 2:

Input:  array1 = {"Java", "JavaScript", "C", "C++" }
array2 = {"Python", "C#", "Java", "C++" }
Output: Common Elements : {"Java", "C++"} 

In the above example, as array1 and array2 both arrays have “Java” and “C++” in common. So, the output array for the above example is {“Java”, “C++”}

In this article, we will discuss different approaches to find the common elements between two array using Java program.

Approach 1: Using the for loop

  • Consider two arrays array1 and array2 and initialize them.

  • Declare an ArrayList to store common elements.

  • Loop through the first array using for loop, take one element from the array, then loop through the second array using another loop to find the same element if the same element is found store in the arraylist and break the inner loop and move on to next element

  • Print the elements using Arraylist

Example

In this example, we initialize two arrays of 5 elements each. Then we declare a Arraylist to store the common elements and we then use two for loops each of them to iterate over two arrays. If we find a commonElement using, then we add the element to the arraylist and add element and break the inner loop. At last, we print the commonElements ArrayList.

import java.util.*; 
public class Main {
   public static void main(String[] args) {
      int[] array1 = {4, 2, 3, 1, 6};
      int[] array2 = {6, 7, 9, 8, 4};
      List<Integer> commonElements = new ArrayList<>();
      for (int i = 0; i < array1.length; i++) {
         for (int j = 0; j < array2.length; j++) {
            if (array1[i] == array2[j]) {
               commonElements.add(array1[i]);
               break;
            }
         }
      }
      System.out.println("Common Elements: " + commonElements);
   }
}

Output

Common Elements: [4, 6]

Time Complexity: O(N^2) Auxiliary Space: O(1)

Approach 2: Using Array.asList() and retainAll() methods

  • Consider two arrays and covert them to lists using Arrays.asList(arrayName).

  • Use retainAll() method to retain the elements of one list which are present in other list and print the elements.

Syntax

collection1.retainAll(collection2)

Here collection1 and collection2 are two collection objects like a list,set,HashSet etc.

This method is used to retain all the elements of one collection in another collection.

Example

In this example, we initialise two arrays and we convert them to ArrayLists by using Arrays.asList() method. Then we use the retainAll() method to find the common elements between two arrays.

import java.util.ArrayList;
import java.util.Arrays;
public class Main {
   public static void main(String[] args) {
      Integer[] array1 = {4, 2, 7, 1, 6};
      Integer[] array2 = {6, 7, 9, 8, 4};
      ArrayList<Integer> list1 = new ArrayList<>(Arrays.asList(array1));
      ArrayList<Integer> list2 = new ArrayList<>(Arrays.asList(array2));
      list1.retainAll(list2);
      System.out.println("Common Elements: " + list1);
   }
}

Output

Common Elements: [4, 7, 6]

Time Complexity: O(N) Auxiliary Space: O(N)

Approach 3.Using Hashset and retainAll() Method

  • Initialize two arrays and convert them into hashset.

  • Use retainAll() method to retain the elements of one list which are present in other list and print the elements.

Example

In this example, we initialise two arrays and we then convert them to HashSets by using Arrays.asList() method and using HashSet() constructor. Then we use the retainAll() method to find the common elements between two arrays.

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Main {
   public static void main(String[] args) {
      Integer[] array1 = {4, 2, 7, 1, 6};
      Integer[] array2 = {6, 7, 9, 8, 4};
      Set<Integer> set1 = new HashSet<>(Arrays.asList(array1));
      Set<Integer> set2 = new HashSet<>(Arrays.asList(array2));
      set1.retainAll(set2);
      System.out.println("Common Elements: " + set1);
   }
}

Output

Common Elements: [4, 6, 7]

Time Complexity: O(N) Auxiliary Space: O(N)

Approach 4: Using Streams

  • Initialize two arrays and convert them into hashset.

  • Convert the set1 to stream and using filter() method find the elements of set2 in set1.

  • Using collect() method convert the elements into set and print them.

Syntax

set1.stream()
   .filter(set2::contains)
   .collect(Collectors.toSet());

Here set1 and set2 are two are two sets withe elements, stream() method is used to convert the set to a stream and then we use the filter method and filter out the elements which are common in both the sets using ‘set2 :: contains’ , then we collect all the common elements using collect() method.

Methods used in this approach

stream() − This method is used to create stream of elements so that we can use methods like filter(),map(),reduce() to process data

Arrays.stream(collection)

filter() − This method is used to filter data from stream i.e, to select specific elements from stream based on a condition.It returns boolean value.

streamobject.filter(condition)

collect() − This method is used to covert stream of elements into collection such as array,set.

streamobject.collect()

Example

In this example, we initialise two arrays and we convert them to Hash Sets by using Arrays.asList() method and using HashSet() constructor. Then we use stream() method to convert set1 to a stream and then we use the filter method and filter out the elements which are common in both the sets using ‘set2 :: contains’. Then we collect all the common elements using collect() method and print the common elements in both the sets.

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
public class Main {
   public static void main(String[] args) {
      Integer[] array1 = {4, 2, 7, 1, 6};
      Integer[] array2 = {6, 7, 9, 8, 4};
      Set<Integer> set1 = new HashSet<>(Arrays.asList(array1));
      Set<Integer> set2 = new HashSet<>(Arrays.asList(array2));
      Set<Integer> commonelements = set1.stream()
      .filter(set2::contains)
      .collect(Collectors.toSet());
      System.out.println("Common Elements: " + commonelements);
   }
}

Output

Common Elements: [4, 6, 7]

Time Complexity: O(N) Auxiliary Space: O(N)

Thus in this article we have discussed different approaches to find the common elements in an array.

Updated on: 10-Apr-2023

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements