==> Scala 中的数据集合:Map、列表、序列、集

==> 集合有两种: 可变集合,不可变集合

        ---> 可变集合    可以对集合进行修改操作

        ---> 不可变集合    集合从不改变,因此可以安全的共享其引用


==> Map

        ---> 可变

1
val employeeInfo = scala.collection.mutable.Map("name"->"Tom""age"->25"gender"->"man")

        ---> 不可变

1
val employeeInfo = scala.collection.immutable.Map("name"->"Tom""age"->25"gender"->"man")


        ---> 操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
val employeeInfo = scala.collection.mutable.Map("name"->"Tom""age"->25"gender"->"man")
 
// 获取集合中的值
employeeInfo("name")        
// 若 Key 不存在,会抛出 Exception,因此,需要进行判断
if (employeeInfo.contains("girlfriend")){
    employeeInfo("girlfriend")
}else{
    -1
}
 
// 可以简写成
employeeInfo.getOrElse("girlfriend", -1)
 
// 可以修改可变集合中的值
employeeInfo("age"= 28
 
// 也可以添加字数
employeeInfo += "girlfriend" -> "如花"


==> 列表

        ---> 可变

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import scala.collection.mutable
 
// 定义一个可变列表
val testList = mutable.LinkedList(1,2,3,4,5)
 
// 对列表进行操作: 将列表中的每个值 乘以 2
// 首先定义一个指针指向列表的开始
var cur = testList
 
// 使用循环操作列表,Nil 相当于 null
while(cur != Nil){
    // elem 相当于一个变量,将循环取出的值赋给此变量,乘以2
    cur.elem = cur.elem * 2
    // 将指针指向下一个元素
    cur = cur.next
}
 
println(testList)



        ---> 不可变

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
定义一个不可变列表
val testList = List(1,2,3,4)
 
定义一个空列表
val testList1:List[Nothing] = List()
 
定义一个二维列表
val testList2:List[List[Int]] = List(List(1,2,3), List(4,5,6))
 
判断列表是否为空
testList.isEmpty
 
查看列表第一个元素
testList.head
 
tail 返回除去第一个元素后其余的所有元素
testList.tail


==> 序列

        ---> Range(2,5)

        ---> (2 to 4)

        ---> (2 until 5)


==> 集 (set)    不重复元素的集合,不保留元素插入的顺序,默认以 Hash 集实现

        ---> 创建集以及操作

1
2
3
4
5
6
7
8
9
10
11
// 创建一个集
var  testSet = Set(1,3,5,9,8)
 
// 向集中添加元素
testSet += "hello"
 
// 判断元素是否存在
testSet contains(3)
 
// 判断一个集是否是它的子集
Set(1,3) subsetOf(testSet)

        ---> 集的运算(并集、交集、差集)

1
2
3
4
5
6
7
8
9
10
11
12
13
var testset1 = Set(1,2,3,4,5,6)
var testset2 = Set(4,5,6,7,8,9)
// 并集
testset1 union testset2
res8: scala.collection.immutable.Set[Int] = Set(516927384)
 
// 交集
testset1 intersect testset2
res10: scala.collection.immutable.Set[Int] = Set(564)
 
// 差集
testset1 diff testset2
res11: scala.collection.immutable.Set[Int] = Set(123)