Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Merge map

Tags:

merge

map

scala

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.

like image 531
Robinho Avatar asked Nov 18 '13 11:11

Robinho


People also ask

Is Scala map a Hashmap?

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.

How do you add a value to a map in Scala?

We can insert new key-value pairs in a mutable map using += operator followed by new pairs to be added or updated.

What is map in Scala?

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) .


1 Answers

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)) 
like image 104
drexin Avatar answered Sep 21 '22 16:09

drexin