Scala添加_2 s在元组列表中
我在Scala中有以下可变的hashmap:
HashMap((b,3), (c,4), (a,8), (a,2))
需要转换为以下内容:
HashMap((b,3), (c,4), (a,10))
我需要诸如dearsbykey函数逻辑之类的东西。
我在这里添加了代码
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)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于PRE 2.13 SCALA版本,您可以尝试使用
Groupby
MAP
:For pre 2.13 Scala versions you can try using
groupBy
withmap
:听起来您所拥有的不是hashmap,而是
m.values
typeiToble [tuple2 [string,int]]
,它更易于管理。在这种情况下,正如评论中的暗示, <代码> groupmapreduce 在一个函数中全部使用。该函数组“匹配”元素在一起,将转换应用于每个元素,然后使用二进制操作减少组。这说明“按元组的第一个元素将值分组,然后保留第二个元素(即数字),然后在每个组中添加所有数字”。这会产生从元组的第一个元素到总和的地图。
请注意,这是
MAP
,不一定是hashmap
。如果您想要hashmap
(即用于Mutability),则需要自己转换。It sounds like what you have is not a hashmap but
m.values
of typeIterable[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.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.
Note that this is a
Map
, not necessarily aHashMap
. If you want aHashMap
(i.e. for mutability), you'll need to convert it yourself.