w3resource

Java: Find the common elements between two arrays


14. Common elements in two string arrays

Write a Java program to find common elements between two arrays (string values).

Pictorial Presentation:

Java Array Exercises: Find the common elements between two arrays


Sample Solution:

Java Code:

// Import the necessary Java utilities package.
import java.util.*;

// Define a class named Exercise14.
public class Exercise14 {
    // The main method where the program execution starts.
    public static void main(String[] args) {
        // Declare and initialize two string arrays, array1 and array2.
        String[] array1 = {"Python", "JAVA", "PHP", "C#", "C++", "SQL"};
        String[] array2 = {"MySQL", "SQL", "SQLite", "Oracle", "PostgreSQL", "DB2", "JAVA"};

        // Print the original contents of array1 and array2.
        System.out.println("Array1 : " + Arrays.toString(array1));
        System.out.println("Array2 : " + Arrays.toString(array2));

        // Create a HashSet to store common elements.
        HashSet set = new HashSet();

        // Iterate through both arrays to find and store common elements.
        for (int i = 0; i < array1.length; i++) {
            for (int j = 0; j < array2.length; j++) {
                // Check if elements in array1 and array2 are equal.
                if (array1[i].equals(array2[j])) {
                    // Add the common element to the HashSet.
                    set.add(array1[i]);
                }
            }
        }

        // Print the common elements.
        System.out.println("Common element : " + (set)); // OUTPUT: [SQL, JAVA]
    }
}

Sample Output:

Array1 : [Python, JAVA, PHP, C#, C++, SQL]                                                                    
Array2 : [MySQL, SQL, SQLite, Oracle, PostgreSQL, DB2, JAVA]                                                  
Common element is : [JAVA, SQL]

Flowchart:

Flowchart: Java exercises: Find the common elements between two arrays


For more Practice: Solve these Related Problems:

  • Write a Java program to find common words between three different arrays of strings.
  • Write a Java program to find common substrings between two arrays of strings.
  • Write a Java program to find common elements while ignoring case sensitivity.
  • Write a Java program to find common elements from multiple string arrays of different lengths.

Go to:


PREV : Find duplicates in string array.
NEXT : Common elements in two integer arrays.

Java Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.