0

I have a list in Scala that I want to group by a key and sum up the values of each key:

val l = List(("abc",1),("abc",2),("cbe",5),("cab",1))

I tried this code:

l.groupBy(identity).mapValues(_.sum) 

But got the following error:

error: type mismatch;
 found   : scala.collection.immutable.Map[(String, Int),Int]
 required: Seq[(String, Int)]

3 Answers 3

3

It might have been already answered in stackoverflow, but you group and then sum the values of list.

scala> val l = List(("abc",1),("abc",2),("cbe",5),("cab",1))
                  .groupBy(_._1)
                  .map { case (k, v) => k -> v.map { _._2}.sum}
l: scala.collection.immutable.Map[String,Int] = HashMap(cbe -> 5, abc -> 3, cab -> 1)
1
  • put everything in one line if you are trying on scala REPL, that way it might be easy. thats directly from my REPL so it must work
    – prayagupa
    Sep 27, 2018 at 18:34
2

Given List:

val list = List(("abc",1),("abc",2),("cbe",5),("cab",1))

Using,

list.groupBy(_._1).mapValues(_.map(_._2).sum)

In Scala REPL:

scala> list.groupBy(_._1).mapValues(_.map(_._2).sum)
res13: scala.collection.immutable.Map[String,Int] = Map(cab -> 1, abc -> 3, cbe -> 5)
0

Can also be done with groupMapReduce

scala> val l = List(("abc",1),("abc",2),("cbe",5),("cab",1))
                 .groupMapReduce(_._1)(_._2)(_ + _)
val l: scala.collection.immutable.Map[String,Int] = Map(abc -> 3, cab -> 1, cbe -> 5)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.