Scala : How to group by key and sum the values up in scala and return the list in expected return type

435 Views Asked by At

I am trying to group by key and sum the values up in scala!

But when I perform the below operation, I get the return type as List[(String, Long)] instead of List[InputRecord]

case class InputRecord(FeeDescription: String, FeeAmount: Long)

  val reconInput : List[InputRecord] = List(InputRecord("Visa Auth Fee", 30), InputRecord("Visa Auth Fee", 40),
    InputRecord("Master Network Fee", 50))

Command i tried

reconInput.groupBy(_.FeeDescription).mapValues(_.foldLeft(0L)(_+_.FeeAmount)).toList

I am getting the Expected data in the result but the type of List is different than what I expected

List(InputRecord("Visa Auth Fee", 70), InputRecord("Master Network Fee", 50))

But I get the return type as

List[(String, Long)] 

instead of

List[InputRecord]

When I tried to cast the list to the expected one using the below command

val outputRecord = reconInput.groupBy(_.FeeDescription).mapValues(_.foldLeft(0L)(_+_.FeeAmount)).toList.asInstanceOf[ReconRecord]

i am getting class cast exception

Exception in thread "main" java.lang.ClassCastException: scala.collection.immutable.$colon$colon cannot be cast to 
Sample$InputRecord
1

There are 1 best solutions below

0
m_vemuri On

You're pretty close.

Scala cannot find the relation between the Pair of primitive types (String, Int) and the case class of InputRecord defined by you.


case class InputRecord(FeeDescription: String, FeeAmount: Long)

val reconInput : List[InputRecord] = List(
  InputRecord("Visa Auth Fee", 30),
  InputRecord("Visa Auth Fee", 40),
  InputRecord("Master Network Fee", 50)
)

val output1 = reconInput.groupBy(_.FeeDescription).mapValues(_.foldLeft(0L)(_+_.FeeAmount)).toList
/*

val output1: List[(String, Long)] = List((Master Network Fee,50), (Visa Auth Fee,70))

*/


So you would need to explicitly map your output to the type that you want.

val output2 = output1.map(pair => InputRecord(pair._1, pair._2))
/*

val output2: List[InputRecord] = List(InputRecord(Master Network Fee,50), InputRecord(Visa Auth Fee,70))

*/