w3resource

Scala Map: Find the Difference between two maps

Scala Map Exercise-20 with Solution

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

Sample Solution:

Scala Code:

object FindDifferenceBetweenMapsExample {
  def main(args: Array[String]): Unit = {
    // Create two maps
    val map1 = Map("Red" -> 1, "Green" -> 4, "Blue" -> 2, "Orange" -> 3)
    val map2 = Map("Red" -> 5, "Green" -> 4, "Blue" -> 2, "Pink" -> 3)
    
    // Print the original map
    println("Original map1: " + map1)
    println("Original map2: " + map2)

    // Find the difference between the maps
    val difference = map1 -- map2.keySet

    // Print the result
    println(s"The difference between the maps is: $difference")
  }
}

Sample Output:

Original map1: Map(Red -> 1, Green -> 4, Blue -> 2, Orange -> 3)
Original map2: Map(Red -> 5, Green -> 4, Blue -> 2, Pink -> 3)
The difference between the maps is: Map(Orange -> 3)

Explanation:

In the above exercise,

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

  • Here are the steps we need to follow to determine the difference between the two maps:
  • Retrieve the set of keys from map2 using the keySet method
  • Use the -- operator on map1 and specify the set of keys from map2 to remove those keys and their associated values from map1.

Finally, we print the result using println, including the difference between the two maps.

Scala Code Editor :

Previous: Merge two maps in the Scala program.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.