1. Introduction
A Map is a collection that stores elements as key-value pairs and allows us to map values to unique keys.
In this tutorial, we’ll explore how to merge two different Maps into a single Map in Scala and deal with duplicate keys.
2. Using the ++ Operator
Scala has a very simple ++ operator that allows us to concatenate and merge Iterables.
Let’s define two Maps that map a String to an Int:
val firstMap = Map(1 -> "Apple", 5 -> "Banana", 3 -> "Orange");
val secondMap = Map(5 -> "Pear", 4 -> "Cherry");
Let’s merge these Maps using the ++ operator:
val mergedMap = firstMap ++ secondMap
Map(1 -> Apple, 5 -> Pear, 3 -> Orange, 4 -> Cherry)
The result is a single Map that contains entries from both firstMap and secondMap.
It’s important to note that when merging duplicate keys the value from the second Map prevails.
The 5 key appears twice in our original Maps – with value Banana in firstMap, and Pear in secondMap. Therefore, Pear is the value present in mergedMap, as the ++ operator takes values for duplicate keys from secondMap.
3. Combining Duplicate Iterable Values
If the values in our Map are Iterables, we can combine the values for duplicate keys using a helper function:
def combineIterables[K, V](a: Map[K, Iterable[V]], b: Map[K, Iterable[V]]): Map[K, Iterable[V]] = {
a ++ b.map { case (k, v) => k -> (v ++ a.getOrElse(k, Iterable.empty)) }
}
Let’s define two new Maps that contain List as their value. Both values map to the key 1:
val firstMap = Map(1 -> List(1,2,3))
val secondMap = Map(1 -> List(4,5))
We’ll now use our combineIterables() function to merge them:
val mergedMap = combineIterables[Int, Int](firstMap, secondMap)
Map(1 -> List(4, 5, 1, 2, 3))
Information from both lists remains. On the other hand, if we had used the ++ operator, the resulting mergedMap would have simply contained the value from secondMap since it would have overwritten the value from firstMap.
4. Conclusion
In this article, we looked at how to merge two Maps in Scala using the ++ operator. We also explored how duplicate keys are dealt with.
In addition, we used a helper function that allowed us to preserve Iterable values for duplicate keys.
As always, the code for these examples can be found over on GitHub.