ADVERTISEMENT
ADVERTISEMENT

Java program to find the common strings in two string arrays

In this java program, we are going to find and print the common strings from two string arrays, here we have two string arrays and printing their common strings, which exist in both of the arrays.
Submitted by IncludeHelp, on November 25, 2017

This an example of Java string programs. In this progra, two string arrays are given and we have to find common strings (elements) using java program.

Example:

    Example:
    Input:
    Array 1 elements: C, C++, C#, JAVA, SQL, ORACLE
    Array 2 elements: MySQL, SQL, Android, ORACLE, PostgreSQL, DB2, JAVA 
    Output:
    Common elements: JAVA, ORACLE, SQL

Program to find common strings in two string arrays in java

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

public class ExArrayCommon {
  public static void main(String[] args) {
    // enter string value.
    String[] array1 = {
      "C",
      "C++",
      "C#",
      "JAVA",
      "SQL",
      "ORACLE"
    };

    String[] array2 = {
      "MySQL",
      "SQL",
      "Android",
      "ORACLE",
      "PostgreSQL",
      "DB2",
      "JAVA"
    };

    // print both the string.
    System.out.println("Array1 : " + Arrays.toString(array1));
    System.out.println("Array2 : " + Arrays.toString(array2));

    HashSet < String > set = new HashSet < String > ();

    for (int i = 0; i < array1.length; i++) {
      for (int j = 0; j < array2.length; j++) {
        if (array1[i].equals(array2[j])) {
          set.add(array1[i]);
        }
      }
    }
    // return common elements.
    System.out.println("Common element : " + (set));
  }
}

Output

    Array1 : [C, C++, C#, JAVA, SQL, ORACLE]
    Array2 : [MySQL, SQL, Android, ORACLE, PostgreSQL, DB2, JAVA]
    Common element : [JAVA, ORACLE, SQL]

Java Array Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.