Scala集合
1. 数组
1.1 定长数组Array
/**
* Author: 3zZ.
* Date: 2020/1/8 7:56 下午
*/
object ArrayApp extends App {
val a = new Array[String](5) // Array(null,...null)
a.length // 5
a(1) = "hello"
a(1) // String = "hello"
val b = Array("hadoop", "spark", "storm")
b(1) = "flink"
b // Array(hadoop, flink, storm)
val c = Array(2,3,4,5,6,7,8,9)
c.sum // Int = 44
c.min // Int = 9
c.max // Int = 2
c.mkString // String = 23456789
c.mkString(",") //String = 2,3,4,5,6,7,8,9
c.mkString("<",",",">") // String = <2,3,4,5,6,7,8,9>
c.toString // String = [I@44e3760b
}
1.2 变长数组ArrayBuffer
/**
* Author: 3zZ.
* Date: 2020/1/8 7:56 下午
*/
object ArrayApp extends App {
val c = scala.collection.mutable.ArrayBuffer[Int]()
c += 1 // ArrayBuffer(1)
c += (2,3,4,5) // ArrayBuffer(1, 2, 3, 4, 5)
c ++= Array(6,7,8) // ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8)
c.insert(0,0) // ArrayBuffer(0, 1, 2, 3, 4, 5, 6, 7, 8)
c.remove(1) // ArrayBuffer(0, 2, 3, 4, 5, 6, 7, 8)
c.remove(0,3) // ArrayBuffer(4, 5, 6, 7, 8)
c.trimEnd(2) // ArrayBuffer(4, 5, 6)
c.toArray.mkString // 456(Array类型)
for(ele <- c){
println(ele) // 遍历 4 5 6
}
for(i <- (0 until c.length).reverse) {
println(c(i)) // 逆序 6 5 4
}
}
2. List
2.1 Nil是什么
scala> Nil
scala.collection.immutable.Nil.type = List()
2.2 List使用
/**
* Author: 3zZ.
* Date: 2020/1/9 4:57 下午
*/
object ListApp extends App {
val l = List(1,2,3,4,5) // l: List[Int] = List(1, 2, 3, 4, 5)
l.head // Int = 1
l.tail // List[Int] = List(2, 3, 4, 5)
val l2 = 1 :: Nil // l2: List[Int] = List(1)
val l3 = 2 :: l2 // l3: List[Int] = List(2, 1)
val l4 = 1 :: 2 :: 3 :: Nil // l4: List[Int] = List(1, 2, 3)
val l5 = scala.collection.mutable.ListBuffer[Int]()
l5 += 2 // ListBuffer(2)
l5 += (3,4,5) // ListBuffer(2, 3, 4, 5)
l5 ++= List(6,7,8) // ListBuffer(2, 3, 4, 5, 6, 7, 8)
l5 -= 2 // ListBuffer(3, 4, 5, 6, 7, 8)
l5 -= (1,4) // ListBuffer(2, 3, 5, 6, 7, 8)
l5 --= List(2,3,5,6) // ListBuffer(7, 8)
l5.toList // List[Int] = List(7, 8)
l5.toArray // Array[Int] = Array(1, 3, 4, 5)
l5.head // Int = 1
l5.isEmpty // Boolean = false
l5.tail // scala.collection.mutable.ListBuffer[Int] = ListBuffer(3, 4, 5)
l5.tail.head // Int = 3
def sum(nums:Int*):Int = {
if(nums.length == 0){
0
} else{
nums.head + sum(nums.tail:_*) // 自动把Seq转换为Int*
}
}
sum(1,2,3,4) // Int = 10
}
3. Set
/**
* Author: 3zZ.
* Date: 2020/1/9 6:24 下午
*/
object SetApp extends App{
val set = scala.collection.mutable.Set[Int]()
set += 1 // set.type = Set(1)
set += (2,1) // set.type = Set(1,2)
}
4. Map
5. Option & Some & None
6. Tuple