How can I merge maps like below:
Map1 = Map(1 -> Class1(1), 2 -> Class1(2)) Map2 = Map(2 -> Class2(1), 3 -> Class2(2))
After merged.
Merged = Map( 1 -> List(Class1(1)), 2 -> List(Class1(2), Class2(1)), 3 -> Class2(2))
Can be List, Set or any other collection who has size attribute.
Scala map is a collection of key/value pairs. Any value can be retrieved based on its key. Keys are unique in the Map, but values need not be unique.
We can insert new key-value pairs in a mutable map using += operator followed by new pairs to be added or updated.
A Map is an Iterable consisting of pairs of keys and values (also named mappings or associations). Scala's Predef object offers an implicit conversion that lets you write key -> value as an alternate syntax for the pair (key, value) .
Using the standard lib, you can do it as follows:
// convert maps to seq, to keep duplicate keys and concat val merged = Map(1 -> 2).toSeq ++ Map(1 -> 4).toSeq // merged: Seq[(Int, Int)] = ArrayBuffer((1,2), (1,4)) // group by key val grouped = merged.groupBy(_._1) // grouped: scala.collection.immutable.Map[Int,Seq[(Int, Int)]] = Map(1 -> ArrayBuffer((1,2), (1,4))) // remove key from value set and convert to list val cleaned = grouped.mapValues(_.map(_._2).toList) // cleaned: scala.collection.immutable.Map[Int,List[Int]] = Map(1 -> List(2, 4))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With