Scala添加_2 s在元组列表中

发布于 2025-01-26 15:20:56 字数 491 浏览 1 评论 0 原文

我在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)
  }

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)
  }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

调妓 2025-02-02 15:20:56

对于PRE 2.13 SCALA版本,您可以尝试使用 Groupby MAP

m.values
  .groupBy(_._1)
  .mapValues(_.map(_._2).sum)

For pre 2.13 Scala versions you can try using groupBy with map:

m.values
  .groupBy(_._1)
  .mapValues(_.map(_._2).sum)
月朦胧 2025-02-02 15:20:56

听起来您所拥有的不是hashmap,而是 m.values type iToble [tuple2 [string,int]] ,它更易于管理。在这种情况下,正如评论中的暗示, <代码> groupmapreduce 在一个函数中全部使用。该函数组“匹配”元素在一起,将转换应用于每个元素,然后使用二进制操作减少组。

m.values.groupMapReduce(_._1)(_._2)(_ + _)

这说明“按元组的第一个元素将值分组,然后保留第二个元素(即数字),然后在每个组中添加所有数字”。这会产生从元组的第一个元素到总和的地图。

Map(a -> 10, b -> 3, c -> 4)

请注意,这是 MAP ,不一定是 hashmap 。如果您想要 hashmap (即用于Mutability),则需要自己转换。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文