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已不鼓励使用。
【完】
相关文章推荐
- Windows下Scala环境搭建
- set 命令特殊用法
- You must SET PASSWORD before executing this statement的解决方法
- 批处理 Set 命令详解 让你理解set命令第1/2页
- SQL语句的并集UNION 交集JOIN(内连接,外连接)等介绍
- ASP中set与dim的区别(自己的理解)
- 深入C#中get与set的详解
- sql Set IDENTITY_INSERT的用法
- set_include_path在win和linux下的区别
- JavaScript获取两个数组交集的方法
- jquery中常用的SET和GET
- Windows7下安装Scala 2.9.2教程
- 大家注意vector, list, set, map成员函数erase
- 基于SQL中SET与SELECT赋值的区别详解
- mysql之set与enum的介绍
- php set_magic_quotes_runtime() 函数过时解决方法
- MySQL 查询结果取交集的实现方法
- MySQL的FIND_IN_SET函数使用方法分享
- .net get set用法小结第1/3页
- mysqli_set_charset和SET NAMES使用抉择及优劣分析