w3resource

Scala Programming: Find the common elements between two arrays of strings

Scala Programming Array Exercise-16 with Solution

Write a Scala program to find the common elements between two arrays of strings.

Sample Solution:

Scala Code:

object Scala_Array {
  import scala.collection.mutable.ArrayBuffer
  def main(args: Array[String]): Unit = {
    var array1 = Array("Python", "JAVA", "PHP", "C#", "C++", "SQL");
    var array2 =
      Array("MySQL", "SQL", "SQLite", "Oracle", "PostgreSQL", "DB2", "JAVA");
    println("Array elements are : ")
    for (c <- array1) {
      print(s"${c}, ")
    }
    println("\nSecond array:")
    for (c <- array2) {
      print(s"${c}, ")
    }

    val temp: ArrayBuffer[String] = ArrayBuffer.empty[String]
    for (i <- 0 to array1.length - 1) {
      for (j <- 0 to array2.length - 1) {
        if (array1(i).equals(array2(j))) {
          temp.append(array1(i));
        }
      }
    }
    println("\nCommon elements of the said two arrays:")
    for (c <- temp) {
      print(s"${c}, ")
    }
  }
}

Sample Output:

Array elements are : 
Python, JAVA, PHP, C#, C++, SQL, 
Second array:
MySQL, SQL, SQLite, Oracle, PostgreSQL, DB2, JAVA, 
Common elements of the said two arrays:
JAVA, SQL,

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Scala program to find the common elements between two arrays of integers.
Next: Write a Scala program to remove duplicate elements from an array of strings.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/scala-exercises/array/scala-array-exercise-16.php