简体   繁体   中英

Transforming Seq[(A, Future[B])] into a Future[Map[A,B]] in Scala

I'm looking for a clean way to transform a Seq[(A, Future[B])] into a Future[Map[A,B]] . Is there a good way to do this? Thanks in advance!

If you're allowed scalaz then yes:

val original:Seq[(String,Future[Int])] = Seq("a" -> Future.successful(1))
val transformed:Future[Map[String,Int]] = original.toMap.sequenceU

You can transform Futures using map and flatMap. Using that, you can just start with an Future computing the empty map and the use flatMap and map to aggregate the other futures:

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

or

val s = Seq( ("1", f1), ("2", f2) )
Future.sequence( s.map { case (k ,v) => v.map(fv => (k ,fv)) } ).map(_.toMap)

This is not hard. You need three steps:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM