简体   繁体   English

地图的Scala值

[英]Scala Sum of Values of a Map

New to scala .. I wanted to calculate the sum of all elements in List which is a value of a map. 新的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

I wanted to creates a Map of 我想创建一个Map of Map
a -> 40 a - > 40
b -> 25 b - > 25

I understand I can use group by on the list which will give me a list of test values, but I am not sure how to operate on that. 我知道我可以在列表中使用group by,它会给我一个测试值列表,但我不知道如何操作。

Thanks! 谢谢!

Using groupBy creates a Map where the values are a list of all matching objects: 使用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)))

From there you can use mapValues to transform the values of the map, first selecting the noOfShares attribute and then sum these: 从那里你可以使用mapValues来转换地图的值,首先选择noOfShares属性,然后对它们sum

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

Note that mapValues only creates a view on the original Map , this means the _.map(_.noOfShares).sum -part is applied every time the result is accessed (even when assigning it to a val before). 请注意, mapValues仅在原始Map上创建一个视图 ,这意味着每次访问结果时都会应用_.map(_.noOfShares).sum -part(即使之前将其分配给val )。 To get a plain Map with only the result, you can call view.force on it: 要获得仅包含结果的普通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)

Here you go. 干得好。

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

first, you create groups with groupBy like this: 首先,您使用groupBy创建组,如下所示:

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

after that you convert the element's values to the sum of Test's noOfShares 之后,将元素的值转换为Test的noOfShares之和

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM