在Scala中反转/转置一对多映射 [英] Reverse / transpose a one-to-many map in Scala

查看:1036
本文介绍了在Scala中反转/转置一对多映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

地图[A,Set [B]] 变成地图[B,集[A]]的最佳方法是什么

What is the best way to turn a Map[A, Set[B]] into a Map[B, Set[A]]?

例如,如何转换

Map(1 -> Set("a", "b"),
    2 -> Set("b", "c"),
    3 -> Set("c", "d"))

b $ b

Map("a" -> Set(1),
    "b" -> Set(1, 2),
    "c" -> Set(2, 3),
    "d" -> Set(3))


b $ b

(我在这里使用不可变集合,而我的真正问题与字符串或整数无关。)

(I'm using immutable collections only here. And my real problem has nothing to do with strings or integers. :)

推荐答案

使用aioobe和Moritz的帮助:

with help from aioobe and Moritz:

def reverse[A, B](m: Map[A, Set[B]]) =
  m.values.toSet.flatten.map(v => (v, m.keys.filter(m(_)(v)))).toMap

如果你显式调用contains,它会更容易阅读:

It's a bit more readable if you explicitly call contains:

def reverse[A, B](m: Map[A, Set[B]]) =
  m.values.toSet.flatten.map(v => (v, m.keys.filter(m(_).contains(v)))).toMap

这篇关于在Scala中反转/转置一对多映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆