简体   繁体   English

将元素添加到作为地图值的scala集

[英]Adding element to a scala set which is a map value

I have the following map in Scala: 我在Scala中有以下地图:

var m = Map[Int,Set[Int]]()
m += 1 -> Set(1)
m(1) += 2

I've discovered that the last line doesn't work. 我发现最后一行不起作用。 I get "error: reassignment to val". 我得到“错误:重新分配到val”。

So I tried 所以我试过了

var s = m(1)
s += 2

Then when I compared m(1) with s after I added 2 to it, their contents were different. 然后当我在添加2之后将m(1)s进行比较时,它们的内容是不同的。 So how can I add an element to a set which is the value of a map? 那么如何将一个元素添加到一个集合中,这是一个映射的值?

I come from a Java/C++ background so what I tried seems natural to me, but apparently it's not in Scala. 我来自Java / C ++背景,所以我尝试的对我来说似乎很自然,但显然它不在Scala中。

You're probably using immutable.Map . 你可能正在使用immutable.Map You need to use mutable.Map , or replace the set instead of modifying it with another immutable map. 您需要使用mutable.Map ,或者替换该集合,而不是使用另一个不可变映射来修改它。

Here's a reference of a description of the mutable vs immutable data structures . 这是对可变与不可变数据结构的描述的引用。

So... 所以...

import scala.collection.mutable.Map
var m = Map[Int,Set[Int]]()
m += 1 -> Set(1)
m(1) += 2

In addition to @Stefan answer: instead of using mutable Map, you can use mutable Set 除了@Stefan回答:而不是使用可变Map,你可以使用可变Set

import scala.collection.mutable.{Set => mSet}
var m = Map[Int,mSet[Int]]()
m += 1 -> mSet(1)
m(1)+=2

mSet is a shortcut to mutable Set introduced to reduce verbosity. mSet是可变集的快捷方式,用于减少冗长。

scala> m
res9: scala.collection.immutable.Map[Int,scala.collection.mutable.Set[Int]] = Map(1 -> Set(2, 1))

I think what you really want here is a MultiMap 我觉得你真正想要的是一个MultiMap

import collection.mutable.{Set, Map, HashMap, MultiMap}
val m = new HashMap[Int,Set[Int]] with MultiMap[Int, Int]
m.addBinding(1,1)
m.addBinding(1,2)
m.addBinding(2,3)

Note that m itself is a val , as it's the map itself which is now mutable, not the reference to the map 请注意, m本身是一个val ,因为它是地图本身,现在是可变的,而不是对地图的引用

At this point, m will now be a: 此时, m现在将成为:

Map(
  1 -> Set(1,2),
  2 -> Set(3)
)

Unfortunately, there's no immutable equivalent to MultiMap, and you have to specify the concrete subclass of mutable.Map that you'll use at construction time. 不幸的是,没有与MultiMap不可变的等价物,你必须指定你在构造时使用的mutable.Map的具体子类。

For all subsequent operations, it's enough to just pass the thing around typed as a MultiMap[Int,Int] 对于所有后续操作,只需传递类型为MultiMap[Int,Int]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM