Java Program to Find the Intersection of Two Arrays of String

In the previous article, we have seen  Java Program to Find Continuous Sub array Whose Sum is Equal to a Given Number

In this article we are going to see how to find the intersection of two arrays of String.

Java Program to Find the Intersection of Two Arrays of String

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see different ways to find the intersection of two arrays of String.

Method-1: Java Program to Find the Intersection of Two Arrays of String By Using  retainAll() method

Approach:

  1. Create two HashSets using given two arrays.
  2. then use retainAll() method of HashSet to retain only common elements from the two sets.

Program:

import java.util.Arrays;
import java.util.HashSet;

public class Main 
{
    public static void main(String[] args) 
    {
        String[] s1 = { "a", "b", "d" };
        String[] s2 = { "a", "b", "c", "d", "e" };
        print_intersection(s1, s2);

    }

    static void print_intersection(String[] s1, String[] s2) 
    {

        HashSet<String> set1 = new HashSet<>(Arrays.asList(s1));

        HashSet<String> set2 = new HashSet<>(Arrays.asList(s2));

        set1.retainAll(set2);

        System.out.println("Intersection: " + set1);
    }

}


Output:

Intersection: [a, b, d]

Method-2: Java Program to Find the Intersection of Two Arrays of String By Dynamic Initialization of Array Elements

Approach:

  1. Iterate both the given arrays.
  2. Compare each element of one array with elements of other array.
  3. If the elements are found to be equal, add that element into HashSet.

Program:

import java.util.HashSet;
import java.util.Scanner;

public class Main 
{
    public static void main(String[] args) 
    {
        // create scanner class object
        Scanner sc = new Scanner(System.in);
        // take input from user for array size
        System.out.print("Enter the size of array: ");
        int n = sc.nextInt();
        // extra Scanner.nextLine() to consume the newline character due to
        // enter key else it will skip the next nextLine() inside the loop.
        sc.nextLine();
        // initialize array with size n
        String[] s1 = new String[n];
        // take input from user for array elements
        System.out.println("Enter array elements: ");
        for (int i = 0; i < n; i++) {
            s1[i] = sc.nextLine();
        }
        System.out.print("Enter the size of array: ");
        int m = sc.nextInt();
        // extra Scanner.nextLine() to consume the newline character due to
        // enter key else it will skip the next nextLine() inside the loop.
        sc.nextLine();
        // initialize array with size m
        String[] s2 = new String[m];
        // take input from user for array elements
        System.out.println("Enter array elements: ");
        for (int i = 0; i < m; i++) {
            s2[i] = sc.nextLine();
        }
        print_intersection_iterative(s1, s2);

    }

    static void print_intersection_iterative(String[] s1, String[] s2) 
    {
        HashSet<String> set = new HashSet<String>();

        for (int i = 0; i < s1.length; i++)
        {
            for (int j = 0; j < s2.length; j++)
            {
                if(s1[i].equals(s2[j]))
                {
                    set.add(s1[i]);
                }
            }
        }

        System.out.println("Intersection: " + set);
    }

}

Output:

Enter the size of array: 4
Enter array elements: 
a
b
c
d
Enter the size of array: 3
Enter array elements: 
a
f
d
Intersection: [a, d]

Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.

Related Java Programs: