Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala combine Seq of Timestamps

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?

like image 636
Biff Wellington Avatar asked Dec 05 '25 11:12

Biff Wellington


1 Answers

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) 
like image 177
cmbaxter Avatar answered Dec 08 '25 01:12

cmbaxter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!