Seq集合
1. Seq简介
Seq表示有序可重复的数据序列, 它本身是一个trait, 所以无法直接构建对象,一般使用伴生对象的apply方法。apply方法底层采用List集合实现。如下图所示:
2. 不可变序列
2.1 List
- 创建定义List
scala
def main(args: Array[String]): Unit = {
// 空集合
val ll = List()
// 为了操作方便,使用特殊对象Nil表示空集合
val seq: Seq[Int] = Seq.apply(1, 3, 5, 6)
// 可以省略apply
val seq1: Seq[Int] = Seq[Int](1, 3, 5, 6)
val list: List[Int] = List[Int](2, 4, 7, 9)
println(seq)
println(seq1)
println(list)
}
运行结果: 2. 操作List
类似Java中的String,可以通过运算符+
进行操作,List也有丰富的一系列的运算符
scala
def main(args: Array[String]): Unit = {
// 使用运算符操作List
// 默认情况下,不可变的集合数据操作,都会产生新的集合
val list1: List[Int] = List[Int](2, 4, 7, 9)
val list2: List[Int] = List[Int](1, 3, 5, 6)
val list3 = list1 :+ 5
val list4 = 5 +: list2
println(list3)
println(list4)
val list5: List[Int] = list1.updated(2, 8)
println(list5)
val list6 = list1.+:(10)
println(list6)
// 访问元素
println(list6(0))
println(list6.mkString(", "))
list6.foreach(println)
// ::的运算规则从右向左,向集合添加元素
val list7 = 7::6::5::list6 // 等价于 list6.::(5).::(6).::(7)
println(s"list7:${list7}")
val list8 = 1 :: 6 :: 9 :: Nil // 等同于1::6::9::List()
println(list8)
val list9 = list6 :: list7
println(s"list9:${list9}")
// 集合间合并:将一个整体拆成一个一个的个体,称为扁平化, 使用:::
val list10 = 1 :: 6 :: list8 ::: list7
println(list10)
}
运行结果:
3. 可变集合
3.1 ListBuffer
- 创建定义ListBuffer
类型Java中的StringBuilder,有专门的方法API进行操作数据。
scala
def main(args: Array[String]): Unit = {
val listBuffer = ListBuffer(1, 3, 8, 100, 89)
println(listBuffer)
}
- 操作ListBuffer
scala
def main(args: Array[String]): Unit = {
val listBuffer1 = ListBuffer(1, 3, 8, 100, 89)
val listBuffer2 = ListBuffer(7, 2)
println(listBuffer1)
// 追加元素
listBuffer1.append(99)
listBuffer1.append(88, 33)
// 批量追加
listBuffer2.appendAll(listBuffer1)
// 插入指定位置的元素
listBuffer2.insert(0, 0)
// 更新指定位置的数据
listBuffer1.update(0, 10)
// updated更改后可以创建新的ListBuffer
val listBuffer3 = listBuffer1.updated(1, 20)
println(s"listBuffer3:${listBuffer3}")
// 删除元素
// 指定删除的元素位置
listBuffer3.remove(2)
println(listBuffer3)
// 第一个参数为位置, 第二个参数为要删除的数量
listBuffer3.remove(3, 2)
println(listBuffer3)
}
运行结果: 3. 可变和不可变互相转换
scala
def main(args: Array[String]): Unit = {
val listBuffer1 = ListBuffer(1, 3, 8, 100, 89)
// ListBuffer转换成List
val list1 = listBuffer1.toList
println(list1)
val list2 = List(1, 3, 6, 8, 0)
// List转换成ListBuffer
val buffer = list2.toBuffer
println(buffer)
}
运行结果: