Nathan February 2016

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!

Answers


melps February 2016

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


dth February 2016

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


corn_dog February 2016

or

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


Dima February 2016

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 }

Post Status

Asked in February 2016
Viewed 2,393 times
Voted 7
Answered 4 times

Search




Leave an answer