Scala transforming a Seq with Future

 ̄綄美尐妖づ 提交于 2019-12-07 19:09:12

问题


I have a Seq of a tuple that looks like this:

Seq[(Future[Iterable[Type1]], Future[Iterator[Type2]])]

I want to transform this into the following:

Future[Seq([Iterable[Type1], [Iterable[Type2])]

Is this even possible?


回答1:


This should do the trick

val a: Seq[(Future[Iterable[Type1]], Future[Iterable[Type2]])] = ...

val b: Future[Seq[(Iterable[Type1], Iterable[Type2])]] = Future.sequence(a.map{
  case (l, r) => l.flatMap(vl => r.map(vr => (vl, vr)))
})



回答2:


A bit simpler than Till Rohrmann's answer. Not tested, but should work.

val seq: Seq[(Future[Iterable[Type1]], Future[Iterable[Type2]])] = ...

val seq2 = Future.traverse(seq) { case (f1, f2) => f1.zip(f2) } 

Or

val seq1 = seq.map { case (f1, f2) => f1.zip(f2) } 
// Seq[Future[(Iterable[Type1], Iterable[Type2])]]

val seq2 = Future.sequence(seq1)
// Future[Seq([Iterable[Type1], [Iterable[Type2])]

If you actually have Iterator[Type2], as in the question, use f2.map(_.toIterable) instead of just f2.



来源:https://stackoverflow.com/questions/32820332/scala-transforming-a-seq-with-future

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