Biff Wellington
Biff Wellington

Reputation: 117

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?

Upvotes: 3

Views: 186

Answers (1)

cmbaxter
cmbaxter

Reputation: 35463

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) 

Upvotes: 5

Related Questions