Nathan
Nathan

Reputation: 78379

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!

Upvotes: 0

Views: 167

Answers (4)

Dima
Dima

Reputation: 40500

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 }

Upvotes: 0

corn_dog
corn_dog

Reputation: 181

or

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

Upvotes: 1

dth
dth

Reputation: 2337

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

Upvotes: 0

melps
melps

Reputation: 1247

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

Upvotes: 1

Related Questions