The Wayback Machine - https://web.archive.org/web/20241001024210/https://www.geeksforgeeks.org/java-program-to-find-common-elements-between-two-arrays/
Open In App

Java Program to Find Common Elements Between Two Arrays

Last Updated : 29 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given two arrays and our task is to find their common elements. 
Examples:

Input:  Array1 = [“Article”, “for”, “Geeks”, “for”, “Geeks”], 
            Array2 = [“Article”, “Geeks”, “Geeks”]
Output: [Article,Geeks]

Input:  Array1 = [“a”, “b”, “c”, “d”, “e”, “f”], 
            Array2 = [“b”, “d”, “e”, “h”, “g”, “c”]
Output: [b, c, d, e]

Using Iterative Methods         

Approach: 

  1. Get the two java Arrays.
  2. Iterate through each and every element of the arrays one by one and check whether they are common in both.
  3. Add each common element in the set for unique entries.
Java
// Java Program to find common elements
// in two Arrays
// Using iterative method

import java.io.*;
import java.util.*;

class GFG {
    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].equals(arr2[j])) {

                    // add common elements
                    set.add(arr1[i]);
                    break;
                }
            }
        }
        for (String i : set) {
            System.out.print(i + " ");
        }
    }

    // main method
    public static void main(String[] args)
    {

        // create Array 1
        String[] arr1
            = { "Article", "in", "Geeks", "for", "Geeks" };

        // create Array 2
        String[] arr2 = { "Geeks", "for", "Geeks" };

        // print Array 1
        System.out.println("Array 1: "
                           + Arrays.toString(arr1));

        // print Array 2
        System.out.println("Array 2: "
                           + Arrays.toString(arr2));

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

        // Find the common elements
        FindCommonElemet(arr1, arr2);
    }
}

Output
Array 1: [Article, in, Geeks, for, Geeks]
Array 2: [Geeks, for, Geeks]
Common Elements: Geeks for 
  • Time Complexity: O(m * n) where m and n are lengths of the input arrays.
  • Auxiliary Space: O(d) where d is the number of common elements.

Using retainAll() method of HashSet

By using the retainAll() method of the HashSet we can find the common elements between two arrays.

Syntax: 

// This method keeps only the common elements
// of both Collection in Collection1.
Collections1.retainAll(Collections2)

Approach : 

  1. Get the two Arrays.
  2. Create two hashsets and add elements from arrays tp those sets.
  3. Find the common elements in both the sets using Collection.retainAll() method. This method keeps only the common elements of both Collection in Collection1.
  4. Set 1 now contains the common elements only.

Below is the implementation of the above approach:

Java
// Java Program to find common elements
// in two Arrays using hashsets
// and retainAll() method
import java.io.*;
import java.util.*;

class GFG {

    // function to create hashsets
    // from arrays and find
    // their common element
    public static void FindCommonElements(int[] arr1,
                                          int[] arr2)
    {
        // create hashsets
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> 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);
        }

        // use retainAll() method to
        // find common elements
        set1.retainAll(set2);
        System.out.println("Common elements- " + set1);
    }

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

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

        // print Array 1
        System.out.println("Array 1: "
                           + Arrays.toString(arr1));
        // print Array 2
        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: O(m + n)
  • Auxiliary Space: O(m + n)                                                                                                                              

Using HashSet

Approach:

  1. Add all elements of first array into a hashset.
  2. Iterate the second array and check whether element present in hashset using contains method. If contains == true, add the element to result in array.

Below is the implementation of the above approach:

Java
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, 4, 5, 6, 9, 8 };
        findCommonElements(arr1, arr2);
        /* expected output {1,3,4,5,6}
           coming from the above written code 
           that is right 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.remove(arr2[i]);
              /* remove common elements from hashmap
              to avoid duplicates*/
                System.out.print(arr2[i] + " ");
            }
        }
    }
}

Output
1
3
4
5
6
  • Time Complexity: O(m + n)
  • Auxiliary Space: O(m)


Previous Article
Next Article

Similar Reads

Find common elements in two ArrayLists in Java
Prerequisite: ArrayList in Java Given two ArrayLists, the task is to print all common elements in both the ArrayLists in Java . Examples: Input: List1 = ["Hii", "Geeks", "for", "Geeks"], List2 = ["Hii", "Geeks", "Gaurav"] Output: [Hii, Geeks, Geeks] Input: List1 = ["a", "b", "c", "d", "e", "f"], List2 = ["b", "d", "e", "h", "g", "c"] Output:[b, c,
4 min read
Java Program to Print uncommon elements from two sorted arrays
Given two sorted arrays of distinct elements, we need to print those elements from both arrays that are not common. The output should be printed in sorted order. Examples : Input : arr1[] = {10, 20, 30} arr2[] = {20, 25, 30, 40, 50} Output : 10 25 40 50 We do not print 20 and 30 as these elements are present in both arrays. Input : arr1[] = {10, 20
2 min read
Java Program to Find the closest pair from two sorted arrays
Given two sorted arrays and a number x, find the pair whose sum is closest to x and the pair has an element from each array. We are given two arrays ar1[0...m-1] and ar2[0..n-1] and a number x, we need to find the pair ar1[i] + ar2[j] such that absolute value of (ar1[i] + ar2[j] - x) is minimum. Example: Input: ar1[] = {1, 4, 5, 7}; ar2[] = {10, 20
3 min read
Java Program to Find k pairs with smallest sums in two arrays
Given two integer arrays arr1[] and arr2[] sorted in ascending order and an integer k. Find k pairs with smallest sums such that one element of a pair belongs to arr1[] and other element belongs to arr2[]Examples: Input : arr1[] = {1, 7, 11} arr2[] = {2, 4, 6} k = 3 Output : [1, 2], [1, 4], [1, 6] Explanation: The first 3 pairs are returned from th
3 min read
Java.util.Arrays.parallelSetAll(), Arrays.setAll() in Java
Prerequisites : Lambda Expression in Java 8IntUnaryOperator Interface parallelSetAll and setAll are introduced in Arrays class in java 8. parallelSetAll(): It set all the element in the specified array in parallel by the function which compute each element. Syntax: public static void parallelSetAll(double[] arr, IntToDoubleFunction g) Parameters :
5 min read
Difference Between Arrays.toString() and Arrays.deepToString() in Java
The deepToString() method of the Arrays class returns the string representation of the deep contents of the specified Object array. Unlike Arrays. toString(), if the array contains other arrays as elements, the string representation includes their contents, and so on. Arrays.toString(): Returns a string representation of the contents of the specifi
3 min read
Java Program for Common Divisors of Two Numbers
Given two integer numbers, the task is to find the count of all common divisors of given numbers? Input : a = 12, b = 24 Output: 6 // all common divisors are 1, 2, 3, // 4, 6 and 12 Input : a = 3, b = 17 Output: 1 // all common divisors are 1 Input : a = 20, b = 36 Output: 3 // all common divisors are 1, 2, 4 Java Code // Java implementation of pro
2 min read
How to Find the Longest Common Prefix of Two Strings in Java?
In this article, we will find the longest common prefix of two Strings in Java. Examples: Input: String 1= geeksforgeeks, String 2 = geezerOutput: “gee” Input: String 1= flower, String 2 = flightOutput: “fl” Methods to Find the Longest common Prefix of two Strings in JavaBelow are the methods by which we can find the longest common prefix of two St
4 min read
Java Program To Find Longest Common Prefix Using Sorting
Problem Statement: Given a set of strings, find the longest common prefix.Examples: Input: {"geeksforgeeks", "geeks", "geek", "geezer"} Output: "gee" Input: {"apple", "ape", "april"} Output: "ap" The longest common prefix for an array of strings is the common prefix between 2 most dissimilar strings. For example, in the given array {"apple", "ape",
2 min read
Java Program To Find Longest Common Prefix Using Word By Word Matching
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap"Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks”
5 min read
Java Program to Check if two Arrays are Equal or not
Given two given arrays of equal length, the task is to find if given arrays are equal or not. Two arrays are said to be equal if both of them contain the same set of elements and in the same order. Note: If there are repetitions, then counts of repeated elements should be the same for two arrays to be equal. Examples: Input : arr1[] = {1, 2, 5, 4,
5 min read
Java Program to Compare two Boolean Arrays
Two arrays are equal if they contain the same elements in the same order. In java, we can compare two Boolean Arrays in 2 ways: By using Java built-in method that is .equals() method.By using the Naive approach. Examples: Input : A = [true , true , false] A1 = [true, true, false] Output: Both the arrays are equal. Input : A = [true, true, false] A1
3 min read
Java Program to Compare two Double Arrays
Java double array is used to store double data type values only. The default value of the elements in a double array is 0. We can compare two double arrays by two ways: By naive approach of traversing through the whole array and comparing each element.By Arrays.equals() method. Method 1: Naive Approach By Comparing one element at a time by traversi
2 min read
Java Program to Compare two Float Arrays
An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together.The base value is index 0 and the difference between the two indexes is the offset. In this program, we need to compare two arrays having elements of float type. Two arrays are equal if they contain the same element
3 min read
Java Program for Median of two sorted arrays of same size
Write a Java program for a given 2 sorted arrays A and B of size n each. the task is to find the median of the array obtained by merging the above 2 arrays(i.e. array of length 2n). The complexity should be O(log(n)). Examples: Input: ar1[] = {1, 12, 15, 26, 38} ar2[] = {2, 13, 17, 30, 45}Output: 16Explanation:After merging two arrays, we get {1, 2
6 min read
Java Program to Merge Two Arrays
Given two arrays, the task is to merge or concatenate them and store the result into another array. Examples: Input: arr1[] = { 1, 3, 4, 5}, arr2[] = {2, 4, 6, 8}Output: arr3[] = {1, 3, 4, 5, 2, 4, 6, 8} Input: arr1[] = { 5, 8, 9}, arr2[] = {4, 7, 8}Output: arr3[] = {5, 8, 9, 4, 7, 8} Method 1: Using Predefined functionFirst, we initialize two arra
6 min read
Java Program to Count of Array elements greater than all elements on its left and at least K elements on its right
Given an array A[ ] consisting of N distinct integers, the task is to find the number of elements which are strictly greater than all the elements preceding it and strictly greater than at least K elements on its right. Examples: Input: A[] = {2, 5, 1, 7, 3, 4, 0}, K = 3 Output: 2 Explanation: The only array elements satisfying the given conditions
7 min read
Java Program to Store Even & Odd Elements of an Array into Separate Arrays
Given an array with N numbers and separate those numbers into two arrays by odd numbers or even numbers. The complete operation required O(n) time complexity in the best case. For optimizing the memory uses, the first traverse through an array and calculate the total number of even and odd numbers in it. Create two arrays with size calculated after
2 min read
Java Program to Maximize count of corresponding same elements in given Arrays by Rotation
Given two arrays arr1[] and arr2[] of N integers and array arr1[] has distinct elements. The task is to find the maximum count of corresponding same elements in the given arrays by performing cyclic left or right shift on array arr1[]. Examples:   Input: arr1[] = { 6, 7, 3, 9, 5 }, arr2[] = { 7, 3, 9, 5, 6 } Output: 5 Explanation: By performing cyc
3 min read
Java Program to Find the Intersection Between Two Collection
Collection means a set of different classes and interfaces are group together into a single unit that has similar functions are called collection and framework we know very that provides a predefined architecture to represents and manipulate collections in java. Here we will be discussing discuss out how to find the intersection between the two col
4 min read
Java Program to Find difference between sums of two diagonals
Given a matrix of n X n. The task is to calculate the absolute difference between the sums of its diagonal.Examples: Input : mat[][] = 11 2 4 4 5 6 10 8 -12 Output : 15 Sum of primary diagonal = 11 + 5 + (-12) = 4. Sum of primary diagonal = 4 + 5 + 10 = 19. Difference = |19 - 4| = 15. Input : mat[][] = 10 2 4 5 Output : 7 Recommended: Please solve
3 min read
Java Program to Find 2 Elements in the Array such that Difference Between them is Largest
An array is the most efficient data structure that is designed to store and access a group of objects. Given an array of integers, our task is to find out two elements from that array such that the difference between them is the maximum. We will be discussing two approaches: By comparing and checking the difference between every possible pair by ru
4 min read
Java Program for Longest Common Subsequence
LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. For example, "abc", "abg", "bdf", "aeg", '"acefg", .. etc are subsequences of "abcdefg". So a string of length n has 2^n different possible s
4 min read
Merging elements of two different arrays alternatively in third array
Given two arrays arr1[] and arr2[], we need to combine two arrays in such a way that the combined array has alternate elements of both. If one array has extra element, then these elements are appended at the end of the combined array. Input : arr1[] = {1, 2, 3, 4, 5, 6} arr2[] = {11, 22, 33, 44}Output: {1, 11, 2, 22, 3, 33, 4, 44, 5, 6} Input : arr
7 min read
Maximum sum by picking elements from two arrays in order
Given two arrays of size N and two integers X and Y indicating the maximum number of elements, one can pick from array A and array B respectively. At each ith turn, either A[i] or B[i] can be picked. The task is to make the selection that results in the maximum possible sum. Note: It is guaranteed that (X + Y) â‰Ĩ N. Examples: Input: A[] = {1, 2, 3,
14 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
How to Convert Two Arrays Containing Keys and Values to HashMap in Java?
HashMap is part of the Collections framework of java. It stores the data in the form of key-value pairs. These values of the HashMap can be accessed by using their respective keys or the key-value pairs can be accessed using their indexes (of Integer type). HashMap is similar to Hashtable in java. The main difference between HashTable and HashMap i
2 min read
How to Convert LinkedHashMap to Two Arrays in Java?
LinkedHashMap is a pre-defined class in java like HashMap. The only difference between LinkedHashMap and HashMap is LinkedHashMap preserve insertion order while HashMap does not preserve insertion order. LinkedHashMap can convert into two Arrays in java where one array is for key in LinkedHashMap and another array for Values. Example : Input : Link
2 min read
equals() and deepEquals() Method to Compare two Arrays in Java
Arrays. equals() method does not compare recursively if an array contains another array on other hand Arrays. deepEquals() method compare recursively if an array contains another array. Arrays.equals(Object[], Object[]) Syntax : public static boolean equals(int[] a, int[] a2) Parameters : a - one array to be tested for equalitya2 - the other array
3 min read
Compare Two Arrays in Java
While comparing two arrays we can not use "==" operator as it will compare the addresses of the memory block to which both the arrays are pointing. If we want to compare the elements inside the array we need to figure out other ways instead of using arithmetic operators. As we all know arrays data structures possess the property of containing eleme
6 min read
Practice Tags :