在 Scala 中交叉和合并/连接两个地图 [英] Intersection and merge/join two maps in Scala

查看:57
本文介绍了在 Scala 中交叉和合并/连接两个地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两张看起来像这样的地图.

Let's say I have two maps that look something like this.

val m1 = Map(1 -> "One", 2 -> "Two", 3 -> "Three")
val m2 = Map(2 -> 2.0, 3 -> 3.0, 4 -> 4.0)

我想根据键获取交集并返回一个表示合并值的元组.结果看起来像这样.

I want to get the intersection based on the keys and return a tuple that represents the merged values. The result would look like this.

Map(2 -> (Two,2.0), 3 -> (Three,3.0))

我想我可以诉诸于类似的东西

I suppose I can resort to something like

val merged = m1 collect {
  case (key, value) if m2.contains(key) => key -> (value, m2(key))
}

但是没有更惯用的"方式来做到这一点吗?我的直觉类似于我用 Set

But is there no "more idiomatic" way to do that? My intuition was something similar to what I get with Set

val merged = m1.intersect(m2)

推荐答案

m1.keySet.intersect(m2.keySet).map(k => k->(m1(k),m2(k))).toMap
// res0: Map[Int,(String, Double)] = Map(2 -> (Two,2.0), 3 -> (Three,3.0))

获取键的交集,然后将它们map变成一个新的Map.

Get the intersection of the keys and then map them into a new Map.

这篇关于在 Scala 中交叉和合并/连接两个地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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