Scala Seq GroupBy with Future

佐手、 提交于 2019-12-04 05:48:02

问题


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)

I have one collection (data:Seq[First]). There is one function which transforms this sequence to another Seq[Second] after applying groupBy and one future operation. getFutureInt is some function returns 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)

Is there any way to avoid multiple minBy, maxBy?


回答1:


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) }
}



回答2:


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)


来源:https://stackoverflow.com/questions/53704967/scala-seq-groupby-with-future

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!