Scala提供了一套丰富的容器(collection)库,包括列表(List)、数组(Array)、集合(Set)、映射(Map)等。
根据容器中元素的组织方式和操作方式,可以区分为有序和无序、可变和不可变等不同的容器类别
Scala用了三个包来组织容器类,分别是scala.collection 、scala.collection.mutable和scala.collection.immutable。默认引用的不可变的库。
Scala 之collection与Java比较大的不同点是,其对应的不可变容器,在创建时得设定初如值,例如:不可变的scala的List一旦被定义,其值就不能改变,因此声明List时必须初始化。
一、Array
package collection
import scala.collection.mutable.ArrayBuffer
object ArrayDemo {
def main(args: Array[String]): Unit = {
createArr()
mutableArray()
methodArrayDemo()
}
// 1、定长数组,数组的创建
def createArr(): Array[String] = {
/* 创建数组的方式一:推荐使用这种
设定长度,长度不可变但对应的数值是可变的,
默认赋值为空,eg:string默认为null,int默认为0 。。。*/
val a: Array[String] = new Array[String](2)
// 创建数组的方式二:
// val a = new Array[String](2)
// 给数组赋值
a(0) = "aa"
a(1) = "bb"
// 遍历数组:方式一
for (str <- a)
println("方式一:" + str)
// 遍历数组:方式二
for (i <- 0 to a.length - 1)
println("方式二:" + a(i))
// 方式二的另一种写法
(0 to a.length - 1).foreach(i => println("--- 方式二:" + a(i)))
// 遍历数组:方式三,foreach
println("-----------foreach start ----------------")
a.foreach((a1: String) => println(a1 + ' '))
println("-----------foreach end ----------------:")
// 修改数组的值
a(0) = "hello"
for (str <- a)
println("after: " + str)
// 创建数组的方式三: 这种方式报错了
//val a = Array(1, 2)
return a
}
// 2、可变数组
def mutableArray(): Unit = {
// 创建可变数组,前提得先import
val arr = new ArrayBuffer[Int]();
arr.append(21)
arr.append(12)
arr.append(3)
arr.append(3)
for (num <- arr)
println(num)
println("-------- sort after ---------")
val arr2 = arr.sorted
for (num <- arr2)
println(num)
}
// 3、数组常用方法测试
def methodArrayDemo(): Unit = {
val arr = new ArrayBuffer[Int]();
arr.append(21)
arr.append(12)
arr.append(83)
arr.append(3)
arr.append(93)
arr.append(53)
// 数组求和:
println("数组求和:" + arr.sum)
// 获取数组中最大的一个
println("数组中最大值:" + arr.max)
//mkString 把数组拼接成字符串
println("mkString:" + arr.mkString)
//mkString,可传入分割符进行分割, 把数组拼接成字符串
println("mkString(parm):" + arr.mkString("#"))
// 根据下标删除数据
println("删除的数据:" + arr.remove(1))
for (num <- arr) println(" remove(1) after: " + num)
// 删除多个,查看源码知道,第一个参数为删除的起始位置,第二个参数为删除的个数
arr.remove(1, 2)
for (num <- arr) println("remove(1,2) after: " + num)
// 插入数据
arr.insert(3, 11, 22, 33)
for (num <- arr) println("insert after: " + num)
def inCreate = (i: Int) => i + 20
println("inCreate(10): " + inCreate(10))
val strB = arr.map(inCreate) // map 给每个数组中的数加上20
println("before map:" + arr + " , after map:" + strB)
val strS = arr.mkString("|") // 将数组转换成String并以分割符进行分割
println("strS:" + strS)
}
// 4、多维数组
def multiArrayDemo(): Unit = {
// 定义2行3列数组
// var multiDimArr = new Array[Int](new Array[Int](1,2,3),new Array[Int](2,3,4))
// val mulArr = new Array[Int][Int](3)
}
}
二、List
package collection
/**
* 类说明:不同于Java的java.util.List,scala的List一旦被定义,其值就不能改变,因此声明List时必须初始化
*/
object ListDemo {
def main(args: Array[String]): Unit = {
// createList()
listCommonMethod()
listConcat()
}
// 1、创建List方式一:
def createList(): Unit = {
val days = List("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
// 创建List方式二,与上面这种方式一样的效果
val days2 = List.apply("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
/*创建List方式三,
Scala还定义了一个空列表对象Nil,
借助Nil,可以将多个元素用操作符::串起来初始化一个列表*/
val days3 = "Sunday" :: "Monday" :: "Tuesday" :: "Wednesday" :: "Thursday" :: "Friday" :: "Saturday" :: Nil
println("------------------days------------------------")
// 2、遍历数组
for (elem <- days) {
println(elem)
}
println("------------------days2------------------------")
for (elem <- days2) {
println(elem)
}
println("------------------days3------------------------")
for (elem <- days3) {
println(elem)
}
// Make a list element-by-element
val when = "AM" :: "PM" :: List()
// Pattern match
days match {
case firstDay :: otherDays =>
println("The first day of the week is: " + firstDay)
case List() =>
println("There don't seem to be any week days.")
}
}
// 2、list常用方法
def listCommonMethod(): Unit = {
/*Scala还定义了一个空列表对象Nil,
借助Nil,可以将多个元素用操作符::串起来初始化一个列表
注:通过 :: 该方式创建list 必须得借助Nil*/
val listNum = 1 :: 22:: 22:: 22 :: 13 :: 9 :: Nil
// 往list中添加数据常用的方法(+:)
val listNum2 = 2 +: listNum
println(" add num to listNum: " + listNum2)
// 根据下标获取数据
println("获取list的第三个值:" + listNum(2))
// 通过 :: 符号给list追加数据,追加后生的是另一个list
val newList = 9999 :: listNum
println("listNum add after: " + newList)
println("---------------")
println("listNum: " + listNum)
println("---------------")
// head 返回列表第一个元素
// tail 返回一个列表,包含除了第一元素之外的其他元素组合成的List
println("get the first value: " + listNum.head + ",get the tail list: " + listNum.tail)
println("get the list sum: " + listNum.sum)
// 删除list中的前 n 位,当 n 大于list长度则返回空list集
println(" drop list of index : " + listNum.drop(2))
println("listNum mkString : " + listNum.mkString(","))
// 符号(_) 代表获取每个值,取出每个值加100
println(listNum.map(_ + 100).toString + "---------------- map ---------------- " + listNum.map(_ + 100) )
// 过滤
println(" ----- filter ------- : " + List(1, 2, 3, 4, 6, 7, 8, 9, 10) filter (_ % 2 == 0)) //取偶
println("-------- index of : " + listNum.indexOf(22))
println("-------- is exist : " + listNum.exists(_ == 22))
println("-------- is find :" + listNum.find(_ == 22))
println("-------- list length: " + listNum.length)
// 去重
println("distinct before: " + listNum + " ,listNum.distinct after: " + listNum.distinct)
}
// 3、List 的连接
def listConcat(): Unit = {
val list1 = List("one", "two", "three")
val list2 = "zero" :: ("four" :: "five" :: "six" :: Nil)
val list3 = list1 ::: list2
println("list1 :: list2 is " + list3)
val list4 = list1.:::(list2)
println("list1 .::: (list2) is " + list4)
val list5 = List.concat(list1, list2)
println("List.concat(list1, list2) is " + list5)
}
}
三、Map
package collection
/**
* 类说明:Map的简单操作
*/
object MapDemo {
def main(args: Array[String]): Unit = {
// createMap
commonMethodOfMap
}
def createMap(): Unit = {
// 创建空映射
val map = scala.collection.mutable.Map[String, String]()
map.put("test", "123412")
println(map)
val map1 = Map("aa" -> "Scala", "bb" -> "Java")
println(map1)
val map2 = map1 + ("cc" -> "C++")
println(map2)
val map3 : Map[String, String] = Map("aa" -> "Scala", "bb" -> "Java")
println("map3: " + map3)
}
// Map 常用方法
def commonMethodOfMap(): Unit = {
import scala.collection.mutable
val map1 = mutable.Map("aa" -> "Java")
map1.put("bb" , "Java")
map1.put("aa" , "C++")
println("map1" + map1)
println("get value by key: " + map1.get("aa"))
map1.remove("aa")
println("remove by key: " + map1)
val map2:mutable.Map[String,Int] = mutable.Map()
map2.put("one",1)
map2.put("two",2)
println(map2)
if(map2.contains("one")) println(map2.get("one")) else println("the key of one is not exist ...")
for (i <- map2.keys) println("key: " + i)
for (i <- map2.values) println("values: " + i)
// printf 的用法
for ((k,v) <- map2) printf("Code is : %s and name is :%s\n",k,v)
val map3 = map2.map(_._2 + 100)
printf("map3: " + map3)
val map4 = map2.map(_._1 + 100)
printf("map4: " + map4)
}
}
四、Set
package collection
/**
* 集合(set)是不重复元素的容器(collection)
* 集合包括可变集和不可变集,默认为不可变集
*/
import scala.collection.mutable
object SetDemo {
def main(args: Array[String]): Unit = {
// createSet
commonMethodOfSet
}
// 1、集全set的创建及遍历
def createSet(): Unit = {
// 定长set
val set1 = Set("Scala", "Java", "PHP", "Java")
// set 的遍历
for (str <- set1)
println(str)
// 可变set
val set2 = mutable.Set("Scala", "Java", "PHP", "Java")
set2 += "C++"
set2 += "Python"
println(set2)
}
// 2、Set 常用方法
def commonMethodOfSet(): Unit = {
val set1 = Set("Scala", "Java", "PHP")
println("set1:" + set1)
// set 之add 方法,+(elem1: A, elem2: A, elems: A*): HashSet[A]
// Creates a new immutable hash set with additional elements, omitting duplicates.
// val set2 = set1 + "Python2"
val set2 = set1 + "Python" + "Flink"
println("set2:" + set2)
// ++ Creates a new set by adding all elements contained in another collection to this set, omitting duplicates.
// val set3 = set1 ++ "C++"
val set3 = set1 ++ set2
println("set3:" + set3)
// -- Creates a new $coll from this $coll by removing all elements of another
val set4 = set3 -- set1
println("set4:" + set4)
import scala.collection.mutable.HashSet
val hashSet = new HashSet()
// scala 如何给HashSet 赋值
val hashSet2 = hashSet + "test1"
println("hashSet2:" + hashSet2)
import scala.collection.mutable.Set
val set5 = Set("test1")
set5.add("test2")
set5.add("test3")
println("set5: " + set5)
// addString
val set6 = set5.addString(new mutable.StringBuilder())
println("set6:" + set6)
val i = 1 to 10
println(i)
}
}