Ravi
Ravi

Reputation: 65

Sum of Values based on key in scala

I am new to scala I have List of Integers

val list = List((1,2,3),(2,3,4),(1,2,3))    
val sum = list.groupBy(_._1).mapValues(_.map(_._2)).sum    
val sum2 = list.groupBy(_._1).mapValues(_.map(_._3)).sum

How to perform N values I tried above but its not good way how to sum N values based on key

Also I have tried like this

val sum =list.groupBy(_._1).values.sum => error

val sum =list.groupBy(_._1).mapvalues(_.map(_._2).sum (_._3).sum) error

Upvotes: 1

Views: 829

Answers (3)

LeMoN.xaH
LeMoN.xaH

Reputation: 571

using the first element in the tuple as the key and the remaining elements as what you need you could do something like this:

val list = List((1,2,3),(2,3,4),(1,2,3))
list: List[(Int, Int, Int)] = List((1, 2, 3), (2, 3, 4), (1, 2, 3))

val sum = list.groupBy(_._1).map { case (k, v) => (k -> v.flatMap(_.productIterator.toList.drop(1).map(_.asInstanceOf[Int])).sum) }
sum: Map[Int, Int] = Map(2 -> 7, 1 -> 10)

i know its a bit dirty to do asInstanceOf[Int] but when you do .productIterator you get a Iterator of Any

this will work for any tuple size

Upvotes: 0

Evgeny Veretennikov
Evgeny Veretennikov

Reputation: 4229

It's easier to convert these tuples to List[Int] with shapeless and then work with them. Your tuples are actually more like lists anyways. Also, as a bonus, you don't need to change your code at all for lists of Tuple4, Tuple5, etc.

import shapeless._, syntax.std.tuple._
val list = List((1,2,3),(2,3,4),(1,2,3))
list.map(_.toList) // convert tuples to list
  .groupBy(_.head) // group by first element of list
  .mapValues(_.map(_.tail).map(_.sum).sum) // sums elements of all tails

Result is Map(2 -> 7, 1 -> 10).

Upvotes: 2

chengpohi
chengpohi

Reputation: 14217

val sum = list.groupBy(_._1).map(i => (i._1, i._2.map(j => j._1 + j._2 + j._3).sum))
> sum: scala.collection.immutable.Map[Int,Int] = Map(2 -> 9, 1 -> 12)

Since tuple can't type safe convert to List, need to specify add one by one as j._1 + j._2 + j._3.

Upvotes: 0

Related Questions