Scala Seq GroupBy with Future

前端 未结 2 491
粉色の甜心
粉色の甜心 2021-01-28 11:07

I have 2 case classes

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


        
相关标签:
2条回答
  • 2021-01-28 11:42

    You could compute those only once :

     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)
    
    0 讨论(0)
  • 2021-01-28 11:52

    You can get away with just .min, and .max if you define an Ordering for your class:

     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 讨论(0)
提交回复
热议问题