如何从 Scala 中的元组列表构建多重映射?

发布于 2024-12-01 18:40:56 字数 167 浏览 1 评论 0原文

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

Suppose I have a list of tuples List[(A, B)]. What is the best way to convert it to a multimap, which maps A to Set[B]? Can I build an immutable multimap ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

顾铮苏瑾 2024-12-08 18:40:56

我可以构建一个不可变的多重映射吗?

Scala 标准库中的 MultiMap 则不然。当然,您可以自己编写。

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

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

Can I build an immutable multimap ?

Not with the MultiMap in Scala standard library. Of course, you can write your own.

What is the best way to convert it to a multimap?

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)}
马蹄踏│碎落叶 2024-12-08 18:40:56

我有点困惑,Multimap 没有将 A 映射到 Set[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))

I'm a bit confused, Multimap doesn't map A to Set[B], it maps A to B where B can have many values. Since you want something immutable, I'm going to change this to Map[A, Set[B]] which isn't a Multimap but does one of the things you said you wanted.

// 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))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文