set
set 中元素不允许重复
set 中的元素是无序的
创建set
val set1 = Set(1,2,4)不可变
val set2 = scala.collection.mutable.Set(1,2,3) 可变
//增加元素
set2+=4
res65: set2.type = Set(1, 2, 3, 4)
//删除元素
scala> set2 -= 3
res66: set2.type = Set(1, 2, 4)
set2.head//查看第一个元素
res68: Int = 1
scala> set2.tail//查看第一个之后所有元素
res69: scala.collection.mutable.Set[Int] = Set(2)
set2.isEmpty//查看集合是否为空
res70: Boolean = false
set2.min//最小值
res71: Int = 1
set2.max//最大值
res72: Int = 2
集合合并
scala> set2++set3
res73: scala.collection.mutable.Set[Int] = Set(1, 5, 2, 4)
查看两个集合交集
set2.intersect(set3)
res77: scala.collection.mutable.Set[Int] = Set()
集合中的函数
1.sum,max,min
val list1 =List(2,3,4,5,6)
list1: List[Int] = List(2, 3, 4, 5, 6)
scala> list2.sum
res78: Int = 16
scala> list1.sum
res79: Int = 20
scala> list1.max
res80: Int = 6
scala> list2.min
res81: Int = 5
2.filter过滤
list2.filter(_%2==0)//或者list2.filter(e=>e%2==0)
res82: List[Int] = List(6)
3.flatten对集合中包含集合做处理
val list4 = List(list2,list1)
list4: List[List[Int]] = List(List(5, 5, 6), List(2, 3, 4, 5, 6))
scala> list4.flatten
res84: List[Int] = List(5, 5, 6, 2, 3, 4, 5, 6)
4.flatMap Map
list1.map(_*10)
res87: List[Int] = List(20, 30, 40, 50, 60)
val list = List('a','b')
val list5 = list.map(ch=>List(ch,ch.toUpper))//将小写转化成大写
//相当于上面的两步
val list6 = list.flatMap(ch=>List(ch,ch.toUpper))
list6: List[Char] = List(a, A, b, B)
5.forall对集合里面的每一个元素做判断
foreach对集合里面的每一个元素做处理
list1.forall(e=>e>0)
res91: Boolean = true
scala> list1.foreach(println)
2
3
4
5
6
6.foldLeft
//有个初始化值,然后从左开始加
list1.foldLeft(10)(_+_)
res98: Int = 30
flodRight
reduceLeft
list1.reduceLeft(_+_)
res94: Int = 20
//从左往后加
scala> list1
res95: List[Int] = List(2, 3, 4, 5, 6)
reduceRight
从有往前加
list1.reduceRight(_+_)
res96: Int = 20