我正在寻找一种将Seq[(A, Future[B])]
转换为Future[Map[A,B]]
的简洁方法。有没有办法做到这一点?提前谢谢!
答案 0 :(得分:1)
如果你被允许scalaz,那么是:
val original:Seq[(String,Future[Int])] = Seq("a" -> Future.successful(1))
val transformed:Future[Map[String,Int]] = original.toMap.sequenceU
答案 1 :(得分:0)
您可以使用map和flatMap转换Futures。使用它,您可以从Future计算空地图开始,使用flatMap和map来聚合其他期货:
val s = Seq("A" -> Future {1}, "B" -> Future {2})
val m = s.foldLeft(Future.successful(Map[String,Int]())){
case (result, (key, future)) => result.flatMap{
map => future.map{
value => map + (key -> value)
}
}
}
答案 2 :(得分:0)
或
val s = Seq( ("1", f1), ("2", f2) )
Future.sequence( s.map { case (k ,v) => v.map(fv => (k ,fv)) } ).map(_.toMap)
答案 3 :(得分:0)
这并不难。您需要三个步骤:
//1. create a list of future tuples
val futureTuples = Future.map { case (a, futureB) => futureB.map ( a -> _ }
//2. Transorm it to a future list
val futureList = Future.sequence(futureTuples)
//3. Finally, convert list to map:
val futureMap = futureList.map { _.toMap }