【问题标题】:Scala : How to group by key and sum the values up in scala and return the list in expected return typeScala:如何按键分组并在 scala 中对值求和并以预期的返回类型返回列表
【发布时间】:2021-11-23 02:16:09
【问题描述】:

我正在尝试按键分组并在 scala 中汇总值!

但是当我执行以下操作时,我得到的返回类型是 List[(String, Long)] 而不是 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))

我尝试过的命令

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

我在结果中得到了预期的数据,但列表的类型与我的预期不同

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

但我得到的返回类型为

List[(String, Long)] 

而不是

List[InputRecord]

当我尝试使用以下命令将列表转换为预期的列表时

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

我收到类转换异常

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

【问题讨论】:

    标签: scala apache-spark arraylist spark-streaming scala-collections


    【解决方案1】:

    你已经很接近了。

    Scala 无法找到 Pair of original types (String, Int) 和您定义的 InputRecord 的 case 类之间的关系。

    
    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))
    
    */
    
    
    

    因此,您需要将输出显式映射到您想要的类型。

    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))
    
    */
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-18
      • 2018-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 2015-03-29
      相关资源
      最近更新 更多