Search code examples
scaladictionarytuplesseq

reduce variable number of tuples Sequences to Map[Key, List[Value]] in Scala


I have two sequences:

Seq("a" -> 1, "b" -> 2)
Seq("a" -> 3, "b" -> 4)

What I want is a result Map that looks like this:

Map(a -> List(3, 1), b -> List(4, 2))

Solution

  • val s1 = Seq("a" -> 1, "b" -> 2)
    val s2 = Seq("a" -> 3, "b" -> 4)
    
    val ss = s1 ++ s2
    
    val toMap = ss.groupBy(x => x._1).map { case (k,v) => (k,  v.map(_._2))}
    
    res0: scala.collection.immutable.Map[String,Seq[Int]] = Map(b -> List(2, 4), a -> List(1, 3))
    

    You can sort this or something you want.