user4941253
user4941253

Reputation:

How to apply sum and groupby on a list in Scala?

I am trying to use groupby method on transactionDay and take the sum of the transactionAmount. and print the output.

case class Transaction(
  transactionId: String,
  accountId: String,
  transactionDay: Int,
  category: String,
  transactionAmount: Double)

I created a list like this:

val transactions: List[Transaction] = transactionslines.map { line =>
  val split = line.split(',')
  Transaction(split(0), split(1), split(2).toInt, split(3), split(4).toDouble)
}.toList

Can anyone help with using the groupBy method.

If you have any documents to share it would be really helpful.

Upvotes: 0

Views: 942

Answers (1)

Ramesh Maharjan
Ramesh Maharjan

Reputation: 41987

Following code should work to get the solution you require

val transactions = transactionslines.map( line => line.split(","))
  .map(split => Transaction(split(0), split(1), split(2).toInt, split(3), split(4).toDouble))
transactions.groupBy(_.transactionDay).mapValues(trans => trans.map(amount => amount.transactionAmount).sum).foreach(println)

Upvotes: 2

Related Questions