如何从Scala中的元组列表构建多图?

Mic*_*ael 23 scala multimap

假设我有一个元组列表List[(A, B)].将其转换为multimap映射A到的a的最佳方法是什么Set[B]?我可以构建一个不可变的 multimap吗?

Ale*_*nov 21

我可以构建一个不可变的多图吗?

不在MultiMapScala标准库中.当然,你可以自己写.

将其转换为多图的最佳方法是什么?

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)}
Run Code Online (Sandbox Code Playgroud)


Der*_*att 16

我有点糊涂了,Multimap不映射ASet[B],它映射AB哪里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))
Run Code Online (Sandbox Code Playgroud)

  • 你也可以使用`mapValues`,它实际上不会产生新的集合,但会作为值的映射`view`. (6认同)
  • 更清洁:`val m = l groupBy(_._ 1)mapValues(_ map {_._ 2} toSet)` (6认同)
  • 这不是更清洁,只是更少的角色. (4认同)
  • 直接使用map:`list.groupBy(_._ 1).map {case(x,xs)=>(x,xs.map(_._ 2))}` (2认同)