Reputation: 7105
I know that there exists
Future.sequence
to transform a List[Future[T]]
to a Future[List[T]]
is there any way to transform a HashMap[T,Future[N]]
to Future[HashMap[T,N]]
?
Upvotes: 2
Views: 193
Reputation: 15464
There isn't anything built into the standard libraries for this, but it's easy enough to implement, e.g.
def combineFutures[K,V](m: Map[K,Future[V]]): Future[Map[K,V]] = {
m.foldLeft(Future.successful(Map.empty[K, V])) {
case (futureAcc: Future[Map[K, V]], (k: K, futureV: Future[V])) =>
for {
acc <- futureAcc
v <- futureV
} yield acc + (k -> v)
}
}
// Mutable HashMap version
import scala.collection.mutable.HashMap
def combineFutures[K,V](m: HashMap[K,Future[V]]): Future[HashMap[K,V]] = {
m.foldLeft(Future.successful(HashMap.empty[K, V])) {
case (futureAcc: Future[HashMap[K, V]], (k: K, futureV: Future[V])) =>
for {
acc <- futureAcc
v <- futureV
} yield {
acc.put(k, v)
acc
}
}
}
(I've added some extra unnecessary type annotations above for clarity.)
Upvotes: 3
Reputation: 9698
Not sure about an out-of-the-box function, but I'd do it myself like this:
import scala.collection.mutable.HashMap
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
val a: HashMap[Int, Future[Int]] = HashMap((1, Future(42)), (2, Future(43)))
val iterOfFutures = a.map { case (k, v) => v.map(vv => (k, vv)) }
val futureMap: Future[Map[Int, Int]] = Future.sequence(iterOfFutures).map(_.toMap)
futureMap.map(println) // Map(2 -> 43, 1 -> 42)
Thread.sleep(100)
EDIT:
Not the main point of the question, but if you want a mutable HashMap instead of immutable Map then you have to convert it. Here's an ugly-ish way off the top of my head, perhaps there's something nicer:
val futureMap: Future[HashMap[Int, Int]] =
Future.sequence(iterOfFutures).map(s => HashMap(s.toSeq: _*))
Upvotes: 4