Scala:按键合并地图 [英] Scala: Merge maps by key

查看:100
本文介绍了Scala:按键合并地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两张地图:

  val a = Map(1  - >one,2  - > 2,3  - >3)
val b = Map(1 - >un,2 - >deux,3 - >trois)

我想通过键合并这些映射,应用一些函数来收集值(在这种情况下,我想收集它们进入一个seq,给出:

$ pre code> val c = Map(1 - > Seq(one,un), 2-Seq(two,deux),3-Seq(three,trois))

感觉这样做应该有一种很好的,习惯的方式 - 任何建议?如果解决方案涉及到标量,我很高兴。

解决方案

scala。 collection.immutable.IntMap 有一个 intersectionWith 方法,它完全符合你的需要(我相信):

  import scala.collection.immutable.IntMap 

val a = IntMap(1 - > 一,2 - > two,3 - > 三,4 - > 四)
val b = IntMap(1 - >un,2 - >deux,3 - >trois)

val合并= a。 (b,(_,av,bv:String)=> Seq(av,bv))



<这为你提供了 IntMap(1 - > List(one,un),2 - > List(two,deux),3 - > List(three,trois))。请注意,它正确地忽略了只出现在 a 中的关键字。

作为备注:我经常发现自己想要 unionWith , intersectionWith 等函数.org / packages / archive / containers / 0.4.2.0 / doc / html / Data-Map.html> Scala中的Haskell的 Data.Map 。我不认为有任何原则性的理由,他们应该只在 IntMap 中可用,而不是在基础集合中.Map 特质。


Say I have two maps:

val a = Map(1 -> "one", 2 -> "two", 3 -> "three")
val b = Map(1 -> "un", 2 -> "deux", 3 -> "trois")

I want to merge these maps by key, applying some function to collect the values (in this particular case I want to collect them into a seq, giving:

val c = Map(1 -> Seq("one", "un"), 2->Seq("two", "deux"), 3->Seq("three", "trois"))

It feels like there should be a nice, idiomatic way of doing this - any suggestions? Am happy if the solution involves scalaz.

解决方案

scala.collection.immutable.IntMap has an intersectionWith method that does precisely what you want (I believe):

import scala.collection.immutable.IntMap

val a = IntMap(1 -> "one", 2 -> "two", 3 -> "three", 4 -> "four")
val b = IntMap(1 -> "un", 2 -> "deux", 3 -> "trois")

val merged = a.intersectionWith(b, (_, av, bv: String) => Seq(av, bv))

This gives you IntMap(1 -> List(one, un), 2 -> List(two, deux), 3 -> List(three, trois)). Note that it correctly ignores the key that only occurs in a.

As a side note: I've often found myself wanting the unionWith, intersectionWith, etc. functions from Haskell's Data.Map in Scala. I don't think there's any principled reason that they should only be available on IntMap, instead of in the base collection.Map trait.

这篇关于Scala:按键合并地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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