'scala add _2 s in a list of Tuple 2
I have the following mutable Hashmap in Scala:
HashMap((b,3), (c,4), (a,8), (a,2))
and need to be converted to the following:
HashMap((b,3), (c,4), (a,10))
I need something like reduceByKey function logic.
I added the code here
def main(args: Array[String]) = {
val m = new mutable.HashMap[String,Tuple2[String,Int]]()
println("Hello, world")
m.+=(("xx",("a",2)))
m.+=(("uu",("b",3)))
m.+=(("zz",("a",8)))
m.+=(("yy",("c",4)))
println(m.values)
}
Solution 1:[1]
For pre 2.13 Scala versions you can try using groupBy
with map
:
m.values
.groupBy(_._1)
.mapValues(_.map(_._2).sum)
Solution 2:[2]
It sounds like what you have is not a hashmap but m.values
of type Iterable[Tuple2[String, Int]]
, which is more manageable. In that case, as hinted at in the comments, groupMapReduce
does it all in one function. This function groups "matching" elements together, applies a transformation to each element, and then reduces the groups using a binary operation.
m.values.groupMapReduce(_._1)(_._2)(_ + _)
This says "Group the values by the first element of their tuple, then keep the second element (i.e. the number), and then add all of the numbers in each group". This produces a map from the first element of the tuple to the sum.
Map(a -> 10, b -> 3, c -> 4)
Note that this is a Map
, not necessarily a HashMap
. If you want a HashMap
(i.e. for mutability), you'll need to convert it yourself.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Guru Stron |
Solution 2 | Silvio Mayolo |