×

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

Switch Case with Enum in Java

From some conditions, the java switch statement executes one statement. Similar to the If-Else-If ladder statement, this can be Byte, short, int, long, enum, string, and some wrapper types like...

4 minutes read.

Banking Application in Java

JDBC (Java Database Connectivity), which provides an API to connect to, execute, and fetch data from any databases, can be used to handle transactions in Java. There are several factors...

7 minutes read.

Creating a Jar file in Java

The JDK's jar (Java Archive) tool offers the ability to produce jar files that can be executed. If you double-click a jar file that is executable, it will call the...

2 minutes read.

Java Interface Keyword

An interface is also known as the blueprint in Java. It has constants of static values and methods of abstraction. The interface is a mechanism used by Java to declare...

3 minutes read.

String Pool in Java

String Pool in Java: String is one of the most important discussed topics in Java. There are a lot of concepts related to the String and one of them is...

5 minutes read.

Command Class in Java

We use the command class to run commands against the database. The Command class may find a set of parameter objects for use in sending values to a stored procedure...

3 minutes read.

How to avoid deadlock in java

Deadlock: A deadlock is an event that never going to occur. In java, deadlock is just a part of the multithreading. It is an environment that allows us to run multiple...

4 minutes read.

Internal Working of ArrayList in Java

Java's version of a resizable array is called ArrayList. The dynamic growth of an array list ensures that there is always room for new elements. ArrayList's backing data structure is...

8 minutes read.

Java Enum vs Class

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four integrators named Club, Diamond,...

7 minutes read.

Static Array in Java

In this tutorial, we will study static arrays in Java. An array is a data structure that is of great importance in any programming language. It is classified into two...

3 minutes read.

Java Integer toUnsignedString() method

The toUnsignedString() method of Java Integer class returns a string representation of the argument as an unsigned decimal value. The second syntax returns a string representation of the given argument as...

2 minutes read.

Undo and Redo Operations in Java

Undo and redo operation are the most widely used operation while dealing with file. In this section, we will discuss how to implement undo and redo operation in Java. Undo Redo...

2 minutes read.

Program to find the duplicate characters in a string

Problem statement You have given with a string and your task is to find out the repeated characters from the string and print them. If no character is repeated, then you...

2 minutes read.

How to set path in Java

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated Development...

5 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.

ArrayDeque in Java

ArrayDeque The ArrayDeque is one of the essential concepts in java to implement the deque interface. It will allow us to apply a resizable array to implement the Deque interface. This...

8 minutes read.

Shift right zero Fill Operator in Java and Operator Shifting

Left shift operator ( << ) : The left shift operator is an operator which performs its action at the bits level of a binary Operator. That means when you perform...

4 minutes read.

Array and String with Examples in Java

Array in Java: An array in Java is a group of variables with similar types that have a common name. The arrays used in Java differ from those used in C/C++. Key...

6 minutes read.

Matrix Multiplication in Java

In Java, using the binary operator (*) we can perform matrix multiplication. A Matrix is a group of arrays. In the multiplication of matrices, the elements of each row are...

3 minutes read.

How to Convert Binary to Decimal in Java

How to Convert Binary to Decimal in Java There are two methods to convert binary to decimal. Using Integer.parseInt() method Using user-defined logic Using Integer.parseInt() method The parseInt() is a static method of...

2 minutes read.