def foo[A, B](as: Seq[A])(f: A => B)(implicit exc: ExecutionContext)
: Future[Seq[(A, B)]] = {
Future
.traverse(as.toSet)(a => Future((a, (a, f(a)))))
.map(abs => as map abs.toMap)
}
说明:
-
as.toSet
确保
f
对每个
a
-
这个
(a, (a, f(a)))
为您提供一个具有嵌套形状元组的集合
(a, (a, b))
-
映射原始序列
一
由一个
Map
双对
(a,(a,b))
给你一个序列
(a, b)
S.
自从你
f
反正也不是异步的,而且既然您不介意使用futures,您可以考虑使用
par
-收藏:
def foo2[A, B](as: Seq[A])(f: A => B): Seq[(A, B)] = {
as map as.toSet.par.map((a: A) => a -> (a, f(a))).seq.toMap
}