×

Program to Find the Common Elements between two Arrays in Java

In this article, we are going to learn how to find the common elements between two arrays using Java. Here, we use different approaches in Java to find the common elements. We are also going to calculate the time complexities of every program also.

Here, we are using the following approaches to find the common elements between two arrays:

  • Using Iterative method
  • Using Hash sets

Iterative Method Program

In this approach, we follow the following things:

  • Acquire the two Java Arrays.
  • Check to see if there are any elements that are shared by both arrays by iterating through each element one by one.
  • To create individual entries, add each shared element in the set.

Example 1:

import java.io.*;
import java.util.*;
class JTP {
    private static void FindCommonElemet(String[] arr1,
                                         String[] arr2)
    {
        Set<String> set = new HashSet<>();
        for (int i = 0; i < arr1.length; i++) {
            for (int j = 0; j < arr2.length; j++) {
                if (arr1[i] == arr2[j]) {
set.add(arr1[i]);
                    break;
                }
}
        }
        for (String i : set) {
System.out.print(i + " ");
        }
    }


    // main method
    public static void main(String[] args)
    {
         // Creating Array 1
         String[] arr1
            = { "Hi", "I", "Am", "a", "Robot" };
        // Creating Array 2
        String[] arr2 = { "I", "Am", "Robot" };
       // Printing Array 1
System.out.println("Array 1: "
                           + Arrays.toString(arr1));
        // Printing Array2
System.out.println("Array 2: "
                           + Arrays.toString(arr2));


System.out.print("Common Elements: ");


FindCommonElemet(arr1, arr2);
    }
}

Output:

Array 1 - { Hi, I, Am, a, Robot }
Array 2 - { I, Am, Robot}
Common elements – I Am Robot

Time Complexity of the program is: O(n^2)

Auxiliary Space: O(n)

Using Hash sets

In this approach, we follow the following things:

  • Acquire the two Arrays.
  • Create two hash sets then fill them with elements from arrays.
  • Utilize the Collection.retainAll() method to identify the shared elements between the two sets. Only the elements that are shared by both Collections are kept in Collection1 by this method.
  • Now, the common items are in Set 1.

Example 2:

import java.io.*;
import java.util.*;
class JTP {


    public static void FindCommonElements(int[] arr1,
                                          int[] arr2)
    {
        // create hashsets
        Set set1 = new HashSet<>();
        Set set2 = new HashSet<>();


        // Adding elements from array1
        for (int i : arr1) {
            set1.add(i);
        }


        // Adding elements from array2
        for (int i : arr2) {
            set2.add(i);
        }


        set1.retainAll(set2);
System.out.println("Common elements- " + set1);
    }


    // main method
    public static void main(String[] args)
    {
        int[] arr1
            = { 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 };


        int[] arr2 = { 100, 9, 64, 7, 36, 5, 16, 3, 4, 1 };


System.out.println("Array 1: "
                           + Arrays.toString(arr1));
System.out.println("Array 2: "
                           + Arrays.toString(arr2));
FindCommonElements(arr1, arr2);
    }
}

Output:

Array 1 - [1 ,4 ,9 ,16 ,25 ,36 ,49 ,64 ,81 ,100]
Array 2 – [100, 9, 64, 7, 36 ,5 ,16 ,3 ,4 , 1]
Common elements – [16 ,64 ,1 ,4 ,36 ,100 ,9] 

Time complexity for the following program is: O(n)

Auxiliary space for the following program is: O(n)

Example 3:

In this approach, we follow the following things:

  • Create a hashset with the first array's whole contents.
  • Utilizing the includes method, iterate the second array to see if any of the elements are present in the hashset.
  • Add the element to the result in the array if contains
import java.util.HashMap;
public class CommonElementsOfArrays {
    public static void main(String[] args)
    {
        int[] arr1 = new int[] { 1, 2, 3, 4, 5, 6, 7 };
        int[] arr2 = new int[] { 1, 3, 5, 6, 9, 8, 3 };
        findCommonElements(arr1, arr2);
        /* expected output {1,2,3,5,6}
           coming from the above written code {1,2,3,5,6,3}
           that is wrong if not please correct me
        */
    }


    public static void findCommonElements(int arr1[],
                                          int arr2[])
    {
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        for (int i = 0; i < arr1.length; i++) {
            if (hashMap.containsKey(arr1[i])) {
                hashMap.put(arr1[i],
                            hashMap.get(arr1[i]) + 1);
            }
            else {
                hashMap.put(arr1[i], 1);
            }
        }


        for (int i = 0; i < arr2.length; i++) {
            if (hashMap.containsKey(arr2[i])
&& hashMap.get(arr2[i]) > 0) {
                hashMap.put(arr2[i],
                            hashMap.get(arr2[i]) - 1);
                System.out.print(arr2[i] + " ");
            }
        }
    }
}

Output:

1
3
4
5
6

Time Complexity for the above program is: O(n)

Auxiliary Space for the above program is: O(n)


Related Topics

Selection Sort in Java

Selection Sort in Java Selection sort is also a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted portion of the input array, and placing it...

5 minutes read.

Java instance variable

An instance in object-oriented programming (OOP) is a particular implementation of any object. Each realized version of an item, which might vary in several ways, is an instance. Instantiation is...

3 minutes read.

Java throw

Java throw Sometimes it is required in the code to throw an exception deliberately. In order to achieve the same, the Java throw keyword should be used. One can throw either...

3 minutes read.

How to Convert long to int in Java

How to Convert long to int in Java When we assign a larger type value to a variable of smaller type, then we need to perform explicit casting for the conversion....

2 minutes read.

Java vs JavaScript

Java Vs JavaScript Java and JavaScript, both play an important role in the field of Computer Technology. Most people think JavaScript is a part of Java. But it is not entirely...

4 minutes read.

How to check version of java in Linux

Java is one of the most famous and thoroughly utilized programming tongues from one side of the world to the other. On the off chance that you are a Java...

2 minutes read.

Block Swap Algorithm for array rotation in Java

An array and r, the rotation factor by which the array must be rotated, are both provided to us. We must then return the rotated array. A well-known and popular method is...

4 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

Program to check whether a given character is present in a string or not

In this article, you will understand the logic to find out whether the given character is present in the string or not and find out the position of the specified...

3 minutes read.

Java finally

Java finally: There are some statements in a program whose execution is extremely important. For example, closing of a database connection. Statements that do the closing of the database connection...

5 minutes read.

How to Reduce Time Complexity in Java

What is time complexity?  The time complexity in java is given as the amount of time a program requires to run or execute it Calculating the time complexity of the program The time...

4 minutes read.

Add numbers represented by Linked Lists in Java

For calculating the sum of the two numbers that are represented by a linked list, and then store the result in a new linked list. A linked list's head node...

7 minutes read.

Star Pattern Programs in Java

Star Pattern Programs in Java The star pattern programs in Java is the part of pattern programs in Java, which we discussed earlier. Right Triangle Star Pattern Filename: StarPatternExample.java public class StarPatternExample {              public static void...

4 minutes read.

Java Protected Keyword

An access modifier is a keyword that Java protects. It can be used to constructors, methods, inner classes, and variables. Variables, methods, and constructors that have been marked protected in...

3 minutes read.

Java Garbage Collection Interview Questions

One of the key areas of Java is garbage collection. Garbage collection enables apps to manage memory automatically. Interviewers frequently ask inquiries about garbage collection. Q1: What is the purpose of...

6 minutes read.

Java Throw and Throws Keyword

Exceptions in Java enable us to construct high-quality programs where faults are checked at compile time rather than run time and where we may define unique exceptions that make code...

6 minutes read.

Majority Element in Java

It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may...

10 minutes read.

Java Sort String

In this article, you will be acknowledged about how to sort a string in Java. Introduction Firstly, let us revise what is string Strings are collections of characters that are frequently used in...

4 minutes read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

3 minutes read.

Java Comparator Interface

Java comparator interface is used in a situation when we have to sort an object which does not implement Comparable or do sorting in a different way than the Comparable....

1 minute read.