假设我有一个 tuples 列表List[(A, B)]
。multimap
将其转换为映射A
到的最佳方法是什么Set[B]
?我可以构建一个不可变 multimap
的吗?
问问题
9931 次
2 回答
22
我可以构建一个不可变的多图吗?
不是MultiMap
在 Scala 标准库中。当然,你也可以自己写。
将其转换为多图的最佳方法是什么?
import scala.collection.mutable.{HashMap, Set, MultiMap}
def list2multimap[A, B](list: List[(A, B)]) =
list.foldLeft(new HashMap[A, Set[B]] with MultiMap[A, B]){(acc, pair) => acc.addBinding(pair._1, pair._2)}
于 2011-08-26T20:23:01.533 回答
19
我有点困惑,Multimap
不映射A
到Set[B]
,它映射A
到可以有很多值的B
地方。B
既然你想要一些不可变的东西,我将把它改成这Map[A, Set[B]]
不是Multimap
你说你想要的事情之一。
// This is your list of (A, B)
val l = List((1, "hi"),
(2, "there"),
(1, "what's"),
(3, "up?"))
// Group it and snip out the duplicate 'A'
// i.e. it initially is Map[A, List[(A, B)]] and we're going to convert it
// to Map[A, Set[B]]
val m = l.groupBy(e => e._1).mapValues(e => e.map(x => x._2).toSet)
println(m)
// Prints: Map(3 -> Set(up?), 1 -> Set(hi, what's), 2 -> Set(there))
于 2011-08-26T20:07:25.930 回答