scala底子学习(数据范例)-聚集

打印 上一主题 下一主题

主题 1020|帖子 1020|积分 3060

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
聚集

Scala Set(聚集)是没有重复的对象聚集,所有的元素都是唯一的。
Scala 聚集分为可变的和不可变的聚集。
默认情况下,Scala 使用的是不可变聚集,如果你想使用可变聚集,必要引用 scala.collection.mutable.Set 包。
默认引用 scala.collection.immutable.Set,不可变聚集实比方下:
创建聚集

  1. val set1:Set[Int] = Set(1,2,3,4)
  2. println(set1)
复制代码
isEmpty

  1. // 判断是否为为空
  2. println(set1.isEmpty) //false
复制代码
获取数据



  • 用过索引获取
  • 提取列表头:head,提取列表尾:last ,返回元素
  • 从前提取元素:take,从后提取元素:takeRight,返回列表
  1. //返回集合第一个元素
  2. println(set1.head)
  3. println(set1.last)
  4. //1
  5. //4
  6. // 获取集合
  7. println(set1.take(2))
  8. println(set1.takeRight(2))
  9. //Set(1, 2)
  10. //Set(3, 4)
复制代码
添加元素

  1. // 添加元素
  2. var newset = set1 + 6
  3. println(newset)
  4. //Set(1, 6, 2, 3, 4)
  5. // 删除元素,元素不存在无影响
  6. val newset2 = set1 - 99
  7. println(newset2)
  8. //Set(1, 2, 3, 4)
  9. // 连接集合(并集)
  10. println(set1++Set(1,7))
  11. //Set(1, 2, 7, 3, 4)
复制代码
删除元素

实际就是,获取剩余元素新列表,并不是删除


  • 删除头部元素,得到其余元素,tail
  • 删除尾部元素,得到其余元素,init
  • 删除前n个元素drop
  • 删除后n个元素dropRight
  1. println(set1.init)
  2. println(set1.tail)
  3. //Set(1, 2, 3)
  4. //Set(2, 3, 4)
  5. // 参数是选取的个数
  6. println(set1.drop(2))
  7. println(set1.dropRight(2))
  8. //Set(3, 4)
  9. //Set(1, 2)
复制代码
常见方法

filter,map,reduce,fold,dropWhile,find,forall,…,含义方式同其余容器
交集 &

效果都相同返回新聚集
  1. println(Set(1,2,3) & Set(1,4,5))
  2. println(Set(1,2,3).&(Set(1,4,5)))
  3. println(Set(1,2,3).intersect(Set(1,4,5)))
  4. println(Set(1,2,3) intersect Set(1,4,5))
  5. //Set(1)
复制代码
差集 diff –

a -- b,a对b的差集
  1. // 差集
  2. println(Set(1, 2, 3)--Set(1, 4, 5))
  3. println(Set(1, 2, 3) diff Set(1, 4, 5))
复制代码
并集 ++ union

  1. println(Set(1,2,3,4).subsetOf(Set(1,2,3,4,5)),"ldsx")
复制代码
to string

  1. // to string
  2. import scala.collection.mutable.StringBuilder
  3. val sb = new StringBuilder
  4. set1.addString(sb, ", ")
  5. println(sb)
  6. val result = sb.toString
  7. println(result)
  8. // to string
  9. println(set1.toString())
  10. // to string
  11. println(set1.mkString(","))
复制代码
to list

  1. println(set1.toList)
复制代码
to Array

  1. println(set1.toArray)
复制代码
to Map

  1. println(set1.map(key => (key, key * key)))
  2. println(set1.map(key => (key, "1"+key)))
  3. println(set1.map(key => (key, key * key)).toMap)
复制代码
其余常用方法

方法同其余容器范例数据
  1. head,last      
  2. take,takeRight
  3. init,tail
  4. drop dropRight
  5. fold,reduce,sum
  6. dropWhile,
  7. forall,foreach
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

没腿的鸟

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表