w3resource

Scala Map: Find common keys between two maps

Scala Map Exercise-18 with Solution

Write a Scala program to create a map and find the common keys between two maps.

Sample Solution:

Scala Code:

object FindCommonKeysBetweenMapsExample {
  def main(args: Array[String]): Unit = {
    // Create two maps
    val map1 = Map("Red" -> 1, "Green" -> 4, "Blue" -> 2, "Orange" -> 3)
    val map2 = Map("Red" -> 1, "Green" -> 4, "Blue" -> 2, "Pink" -> 3)
    
    // Print the original map
    println("Original map1: " + map1)
    println("Original map2: " + map2)
    
    // Find the common keys between the maps
    val commonKeys = map1.keySet.intersect(map2.keySet)

    // Print the result
    println(s"The common keys between the maps are: $commonKeys")
  }
}

Sample Output:

Original map1: Map(Red -> 1, Green -> 4, Blue -> 2, Orange -> 3)
Original map2: Map(Red -> 1, Green -> 4, Blue -> 2, Pink -> 3)
The common keys between the maps are: Set(Red, Green, Blue)

Explanation:

In this program, we create two maps map1 and map2 using the Map constructor and provide key-value pairs.

We follow these steps to find the common keys between the two maps:

  • Retrieve the set of keys from map1 using the keySet method.
  • Retrieve the set of keys from map2 using the keySet method.
  • Use the intersect method on the set of keys to find the common keys.

Finally, we print the result, including the keys that are common to both maps.

Scala Code Editor :

Previous: Sort by values in ascending order.
Next: Merge two maps in the Scala program.

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/map/scala-map-exercise-18.php