Reputation: 237
I have a list of tuples:
val t = List( (1,2,1.0), (1,3,2.0), (1,2,1.1) )
I want to create a map with t._1
as the key, and as the value a map with t._2
as the key and the sum of t._3
as the value.
val m = Map( (1-> Map((2 -> 2.1), (3 -> 2.0)) )
How can I do this in Scala?
I'd like to accomplish this with pure Scala as opposed to a library, but if a library such as scalaz etc. is (in my completely subjective opinion) a nicer looking solution, I would accept that answer as well.
Upvotes: 3
Views: 268
Reputation: 8996
If you are into one-liners then you might like this:
val t = List( (1,2,1.0), (1,3,2.0), (1,2,1.1) )
t.groupBy(_._1).mapValues(_.groupBy(_._2).mapValues(_.map(_._3).sum))
Result is:
Map(1 -> Map(2 -> 2.1, 3 -> 2.0))
Upvotes: 6
Reputation: 20145
Here's one way:
t.groupBy(_._1).map {
case (outerKey, outerList) =>
outerKey -> outerList.groupBy(_._2).map {
case (innerKey, innerList) =>
innerKey -> innerList.map(_._3).sum
}
}
yields:
Map(1 -> Map(2 -> 2.1, 3 -> 2.0))
Upvotes: 2