Scala Map: Merge two maps in the Scala program
Scala Map Exercise-19 with Solution
Write a Scala program to create a map and merge it with another map.
Sample Solution:
Scala Code:
object MergeMapsExample {
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)
// Merge the maps
val mergedMap = map1 ++ map2
// Print the merged map
println("Merged map:")
println("Original map2: " + mergedMap)
}
}
Sample Output:
Original map1: Map(Red -> 1, Green -> 4, Blue -> 2, Orange -> 3) Original map2: Map(Red -> 5, Green -> 4, Blue -> 2, Pink -> 3) Merged map: Original map2: HashMap(Green -> 4, Pink -> 3, Orange -> 3, Red -> 5, Blue -> 2)
Explanation:
In the above exercise,
First, we create two maps map1 and map2 using the Map constructor and provide key-value pairs.
To merge the maps together, we use the ++ operator and specify map1 followed by map2. This operator concatenates the key-value pairs from both maps, creating a new map.
To display each key-value pair, we iterate over the merged map using println and print the merged map with println.
Scala Code Editor :
Previous: Sort by values in ascending order.
Next: Find the Difference between two maps.
What is the difficulty level of this exercise?
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-19.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics