填充案例类列表

时间:2019-09-18 17:37:06

标签: scala

这是我正在尝试创建类型为case的案例类的列表的类

case class Summary(mean : Double , std : Double, currency : String)

我使用地图和过滤器计算meanstddev,然后压缩结果列表以获得:

List((1.0,0.0), (1.0,0.0))对应于:

List((mean1,stddev1), (mean2,stddev2))

如何将这些值映射到案例类case class Summary(mean : Double , std : Double, currency : String)

整个代码:

package com.stats

import com.data.OrderDetails.OrderInstance
import java.util.Date
import breeze.stats._

class Statistics {

  case class Summary(mean : Double , std : Double, currency : String)

  def getStats(od : List[OrderInstance] , before : Date , after : Date) = {

    val dateInterval = od.filter(x => (x.time.before(before)
      && x.time.after(after)))

    val curr : List[String] = List("BTC" , "LTC" )

    val meanCurrPrice : List[Double] = curr.map(c => mean(od.filter(x => x.code.equalsIgnoreCase(c))
      .map(m => m.price)))

    val stdCurrPrice : List[Double] = curr.map(c => stddev(od.filter(x => x.code.equalsIgnoreCase(c))
      .map(m => m.price)))

   meanCurrPrice.zip(stdCurrPrice)
  }

}

object Statistics {

  def main(args: Array[String]): Unit = {

    val od1 = new OrderInstance(1.0 , "" , 1 , 1.0 , new Date() , "BTC")
    val od2 = new OrderInstance(1.0 , "" , 1 , 1.0 , new Date() , "BTC")
    val od3 = new OrderInstance(1.0 , "" , 1 , 1.0 , new Date() , "LTC")

    //4 hours in the future
    val before : Date = new Date(new Date().getTime + (4 * 60 * 60 * 1000))
    //1444 hours in the past - to be sure!
    val after : Date = new Date(new Date().getTime - (1444 * 60 * 60 * 1000))

    val l  = List(od1 , od2 , od3)

    println(new Statistics().getStats(l , before , after))
  }

}

1 个答案:

答案 0 :(得分:3)

您可以使用zipped来构造案例类

示例:

      case class Summary(mean: Double, std: Double, cur: String)

      val curr: List[String] = List("BTC", "LTC")
      val meanCurrPrice: List[Double] = List(1.0, 0.0)
      val stdCurrPrice: List[Double] = List(1.0, 0.0)
      val result = (meanCurrPrice, stdCurrPrice, curr).zipped.map(Summary)


      println(result)

将输出

List(Summary(1.0,1.0,BTC), Summary(0.0,0.0,LTC))