【问题标题】:Scala Sum of Values of a Map地图值的Scala总和
【发布时间】:2016-04-04 10:38:32
【问题描述】:

Scala 的新手.. 我想计算 List 中所有元素的总和,这是一个地图的值。

case class Test(shareClass:String, noOfShares:Long){}

val list = new Test("a", 10)::new Test("b",20)::new Test("a",30)::new Test("b", 5)::Nil

我想创建一个
的地图 一个 -> 40
b -> 25

我知道我可以在列表中使用 group by,这会给我一个测试值列表,但我不知道如何操作。

谢谢!

【问题讨论】:

    标签: scala


    【解决方案1】:

    使用groupBy 创建一个Map,其中的值是所有匹配对象的列表:

    scala> list.groupBy(_.shareClass)
    res0: scala.collection.immutable.Map[String,List[Test]] = Map(b -> List(Test(b,20), Test(b,5)), a -> List(Test(a,10), Test(a,30)))
    

    从那里您可以使用mapValues 转换地图的值,首先选择noOfShares 属性,然后选择sum 这些:

    scala> list.groupBy(_.shareClass).mapValues(_.map(_.noOfShares).sum)
    res1: scala.collection.immutable.Map[String,Long] = Map(b -> 25, a -> 40)
    

    注意mapValues only creates a view on the original Map,这意味着_.map(_.noOfShares).sum-part 应用每次结果被访问(即使之前将它分配给val)。要获得只有结果的普通 Map,您可以在其上调用 view.force

    scala> list.groupBy(_.shareClass).mapValues(_.map(_.noOfShares).sum).view.force
    res2: scala.collection.immutable.Map[String,Long] = Map(b -> 25, a -> 40)
    

    【讨论】:

    【解决方案2】:

    给你。

    case class Test(shareClass: String, noOfShares: Long) {}
    
    val list = new Test("a", 10) :: new Test("b", 20) :: new Test("a", 30) :: new Test("b", 5) :: Nil
    
    val list2 = list.groupBy((_.shareClass))
      .map({ case (a, b) => (a, b.map(_.noOfShares).sum) })
    
    println((list2)) // Map(b -> 25, a -> 40)
    

    【讨论】:

    • 我喜欢使用case (a,b)来避免test._1, test._2
    【解决方案3】:
    case class Test(shareClass: String, noOfShares: Long) {}
    
      val list = Test("a", 10) :: Test("b", 20) :: Test("a", 30) :: Test("b", 5) :: Nil
    
      println(list.groupBy(_.shareClass).map(test => (test._1 -> test._2.foldLeft(0L)((o, n) => o + n.noOfShares))))
    

    首先,您使用 groupBy 像这样创建组:

    Map(b -> List(Test(b,20), Test(b,5)), a -> List(Test(a,10), Test(a,30)))
    

    之后,您将元素的值转换为 Test 的 noOfShares 的总和

    【讨论】:

      猜你喜欢
      • 2013-12-05
      • 1970-01-01
      • 2018-09-09
      • 1970-01-01
      • 2011-03-17
      • 2017-07-30
      • 2016-11-15
      • 1970-01-01
      • 2020-08-28
      相关资源
      最近更新 更多