[英]Scala: Set operations that update the collection?
I am looking at the mutable Set
class and see union
, intersect
, diff
, etc. All of these set operations create a new Set
. 我正在查看可变的
Set
类,并查看union
, intersect
, diff
等。所有这些set操作都会创建一个新的Set
。 I was curious if there is a way to update the Set
rather than create a new one. 我很好奇是否有一种方法可以更新
Set
而不是创建一个新Set
。 Otherwise, I have to switch from val
to var
or I have to follow up with additional steps. 否则,我必须从
val
切换到var
或者必须执行其他步骤。
In case I'm not being clear, consider .NET's HashSet
class. 如果我不清楚,请考虑.NET的
HashSet
类。 It has IntersectWith
, ExceptWith
and UnionWith
that modify the collection. 它具有
IntersectWith
, ExceptWith
和UnionWith
来修改集合。 Whereas the LINQ extension methods Intersect
, Except
and Union
create new collections. 而LINQ扩展方法
Intersect
, Except
和Union
创建新的集合。 I'm hoping to find something equivalent to the "With" variants. 我希望找到与“ With”变体等效的东西。
Here's an inefficient approach that rebuilds the collection from scratch: 这是一种从头开始重建集合的低效方法:
val temp = original.diff(other)
original.clear()
original ++= temp
Obviously, it would be more efficient to do this: 显然,这样做会更有效:
for (value <- other if original.contains(value)) {
original.remove(value)
}
See: http://docs.scala-lang.org/overviews/collections/sets.html#operations-in-class-mutableset 请参阅: http : //docs.scala-lang.org/overviews/collections/sets.html#operations-in-class-mutableset
For example: 例如:
Additions: xs += x Adds element x to set xs as a side effect and returns xs itself.
添加:xs + = x添加元素x以将xs设置为副作用,并返回xs本身。
So just ignore the returned value. 因此,只需忽略返回的值。 The set should be updated in-place.
该集应就地更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.