Scala Seq GroupBy with Future

loading...


0

我有2个案例类

case class First(firstId: Long, pt: Long, vt: Long)
case class Second(secondId: Int, vt: Long, a: Long, b: Long, c: Long, d: Long)

我有一个集合(数据:Seq [First]) . 在应用groupBy和一个future操作之后,有一个函数将该序列转换为另一个Seq [Second] . getFutureInt是一些函数返回Future [Int]

val output: Future[Seq[Second]] = Future.sequence(data.groupBy(d => (d.vt, getFutureInt(d.firstId))).map
   {case(k, v) => k._2.map { si => Second(si, k._1, v.minBy(_.pt).pt,
     v.maxBy(_.pt).pt, v.minBy(_.pt).pt, v.maxBy(_.pt).pt)}}.toSeq)

有没有办法避免多个minBy,maxBy?

loading...

2回答

  • 0

    如果为您的 class 定义 Ordering ,您可以使用 .min.max

    implicit val ordering = Ordering.by[First, Long](_.pt)
    
    futures.map { case(k, v) => 
      k._2.map { si => Second(si, k._1, v.min.pt, v.max.pt, v.min.pt, v.max.pt) }
    }
    

  • 0

    你只能计算一次:

    val output: Future[Seq[Second]] = Future.sequence(data.groupBy(d => (d.vt, getFutureInt(d.firstId))).map
      {case(k, v) => k._2.map { si => {
        val minV = v.minBy(_.pt)
        val maxV = v.maxBy(_.pt)
        Second(si, k._1, minV.pt,
          maxV.pt, minV.pt, maxV.pt)
      }}}.toSeq)
    
评论

暂时没有评论!