您的位置:首页 > 其它

scala中集合的交集、并集、差集

2016-05-25 08:09 441 查看

交集:

scala> Set(1,2,3) & Set(2,4)   // &方法等同于interset方法
scala> Set(1,2,3) intersect Set(2,4)


并集:

scala> Set(1,2,3) ++ Set(2,4)
scala> Set(1,2,3) | Set(2,4)   // |方法等同于union方法
scala> Set(1,2,3) union Set(2,4)


差集:

scala> Set(1,2,3) -- Set(2,4) //得到 Set(1,3)
scala> Set(1,2,3) &~ Set(2,4)
scala> Set(1,2,3) diff Set(2,4)


添加或删除元素,可以直接用
+,-
方法来操作,添加删除多个元素可以用元组来封装:

scala> Set(1,2,3) + (2,4)
scala> Set(1,2,3) - (2,4)


另外,对于
非Set集合
,在做交集、并集、差集时必须转换为
Set
,否则元素不去重没有意义。

而对于非Set类型集合元素去重,也有个很好的方法:
distinct
,定义在 GenSeqLike 特质中

这个方法的好处是集合在去重后类型不变,比用Set去重更简洁

scala> List(1,2,2,3).distinct
scala> List(1,2,2,3).toSet.toList


补充,原用于去重的方法
removeDuplicates
已不鼓励使用。

【完】
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  scala 交集 并集 差集 set