w3resource

Scala Map: Find common keys between two maps


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.


Go to:


PREV : Sort by values in ascending order.
NEXT : Merge two maps in the Scala program.

Scala Code Editor :

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.