Sudheer Aedama
Sudheer Aedama

Reputation: 2144

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

Upvotes: 2

Views: 1198

Answers (3)

mohit
mohit

Reputation: 4999

You can try

scala> val seq = Seq("a" -> 1, "b" -> 2) ++ Seq("a" -> 3, "b" -> 4)
seq: Seq[(String, Int)] = List((a,1), (b,2), (a,3), (b,4))

scala> seq groupBy(_._1) mapValues(_ map(_._2))
res9: scala.collection.immutable.Map[String,Seq[Int]] = Map(b -> List(2, 4), a -> List(1, 3))

Upvotes: 1

Mariusz Nosiński
Mariusz Nosiński

Reputation: 1288

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.

Upvotes: 7

Sudheer Aedama
Sudheer Aedama

Reputation: 2144

def reduceToMap[K, V](seqs: Seq[(K, V)]*): Map[K, List[V]] = {
    seqs.reduce(_ ++ _).foldLeft(Map.empty[K, List[V]])((memo, next) =>
      memo.get(next._1) match {
        case None     => memo.updated(next._1, next._2 :: Nil)
        case Some(xs) => memo.updated(next._1, next._2 :: xs)
      }
    )
  }


scala> reduceToMap(Seq("a" -> 1, "b" -> 2), Seq("a" -> 3, "b" -> 4))
res0: Map[String,List[Int]] = Map(a -> List(3, 1), b -> List(4, 2))

scala> reduceToMap(Seq.empty)
res1: Map[Nothing,List[Nothing]] = Map()

Upvotes: 0

Related Questions