1. 程式人生 > >Scala語言之數據集合(5)

Scala語言之數據集合(5)

子集 nta 其余 tor 並集 als 不可變 diff subset

==> Scala 中的數據集合:Map、列表、序列、集

==> 集合有兩種: 可變集合,不可變集合

---> 可變集合 可以對集合進行修改操作

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


==> Map

---> 可變

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

---> 不可變

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


---> 操作

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" -> "如花"


==> 列表

---> 可變

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)



---> 不可變

定義一個不可變列表
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 集實現

---> 創建集以及操作

// 創建一個集
var  testSet = Set(1,3,5,9,8)

// 向集中添加元素
testSet += "hello"

// 判斷元素是否存在
testSet contains(3)

// 判斷一個集是否是它的子集
Set(1,3) subsetOf(testSet)

---> 集的運算(並集、交集、差集)

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(5, 1, 6, 9, 2, 7, 3, 8, 4)

// 交集
testset1 intersect testset2
res10: scala.collection.immutable.Set[Int] = Set(5, 6, 4)

// 差集
testset1 diff testset2
res11: scala.collection.immutable.Set[Int] = Set(1, 2, 3)


Scala語言之數據集合(5)