Hello I'm learning Scala and I have a Seq of object of the following case class:
case class HistoryCounter(time: DateTime, counter:Int)
Now I would like to combine the value of counter based on the timestamp time. To get the sum of all counters where time is on the same day or the same week.
How can you do this? Is one of the collection functions like fold or map capable of doing this?
If you had a List of these case classes called list, one way to do this is like so:
val counts =
list.groupBy(_.time).map{
case (k, v) => (k, v.map(_.counter).sum)
}
Or more succinctly:
list.groupBy(_.time).mapValues(_.map(_.counter).sum)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With