1. 程式人生 > >Scala入門到精通——第三節 Array、List

Scala入門到精通——第三節 Array、List

本節主要內容

  1. 陣列操作實戰
  2. 列表List操作實戰

陣列操作實戰

1 定長陣列

//定義一個長度為10的數值陣列
scala> val numberArray=new Array[Int](10)
numberArray: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
//定義一個長度為10的String型別陣列
scala> val strArray=new Array[String](10)
strArray: Array[String] = Array(null, null, null, null, null, null, null, null
, null, null) //可以看出:複雜物件型別在陣列定義時被初始化為null,數值型被初始化為0 //陣列元素賦值 scala> strArray(0)="First Element" //需要注意的是,val strArray=new Array[String](10) //這意味著strArray不能被改變,但陣列內容是可以改變的 scala> strArray res62: Array[String] = Array(First Element, null, null, null, null, null, null, null, null, null) //另一種定長陣列定義方式 //這種呼叫方式其實是呼叫其apply方法進行陣列建立操作
scala> val strArray2=Array("First","Second") strArray2: Array[String] = Array(First, Second) Scala中的Array以Java中的Array方式實現

2 變長陣列 ArrayBuffer

//要使用ArrayBuffer,先要引入scala.collection.mutable.ArrayBuffer
scala> import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.ArrayBuffer
//建立String型別ArrayBuffer陣列緩衝 scala> val strArrayVar=ArrayBuffer[String]() strArrayVar: scala.collection.mutable.ArrayBuffer[String] = ArrayBuffer() //+=意思是在尾部新增元素 scala> strArrayVar+="Hello" res63: strArrayVar.type = ArrayBuffer(Hello) //+=後面還可以跟多個元素的集合 //注意操作後的返回值 scala> strArrayVar+=("World","Programmer") res64: strArrayVar.type = ArrayBuffer(Hello, World, Programmer) //顯示完整陣列內容 scala> strArrayVar res65: scala.collection.mutable.ArrayBuffer[String] = ArrayBuffer(Hello, World, Programmer) //++=用於向陣列中追加內容,++=右側可以是任何集合 //追加Array陣列 scala> strArrayVar++=Array("Wllcome","To","XueTuWuYou") res66: strArrayVar.type = ArrayBuffer(Hello, World, Programmer, Wllcome, To, Xue TuWuYou) //追加List scala> strArrayVar++=List("Wellcome","To","XueTuWuYou") res67: strArrayVar.type = ArrayBuffer(Hello, World, Programmer, Wllcome, To, Xue TuWuYou, Wellcome, To, XueTuWuYou) //刪除末尾n個元素 scala> strArrayVar.trimEnd(3) scala> strArrayVar res69: scala.collection.mutable.ArrayBuffer[String] = ArrayBuffer(Hello, World, Programmer, Wllcome, To, XueTuWuYou)
//建立整型陣列緩衝
scala> var intArrayVar=ArrayBuffer(1,1,2)
intArrayVar: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 1, 2)

//在陣列索引為0的位置插入元素6
scala> intArrayVar.insert(0,6)

scala> intArrayVar
res72: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(6, 1, 1, 2)

//在陣列索引為0的位置插入元素7,8,9
scala> intArrayVar.insert(0,7,8,9)

scala> intArrayVar
res74: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(7, 8, 9, 6, 1, 1,2)

//從索引0開始,刪除4個元素
scala> intArrayVar.remove(0,4)

scala> intArrayVar
res77: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 1, 2)

//轉成定長陣列
scala> intArrayVar.toArray
res78: Array[Int] = Array(1, 1, 2)

//將定長陣列轉成ArrayBuffer
scala> res78.toBuffer
res80: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1, 1, 2)

3 陣列的遍歷

//to
scala> for(i <- 0 to intArrayVar.length-1) println("Array Element: " +intArrayVar(i))
Array Element: 1
Array Element: 1
Array Element: 2
//until
scala> for(i <- 0 until intArrayVar.length) println("Array Element: " +intArrayVar(i))
Array Element: 1
Array Element: 1
Array Element: 2

//陣列方式(推薦使用)
scala> for(i <- intArrayVar) println("Array Element: " + i)
Array Element: 1
Array Element: 1
Array Element: 2

//步長為2
scala>  for(i <- 0 until (intArrayVar.length,2)) println("Array Element: " +intA
rrayVar(i))
Array Element: 1
Array Element: 2

//倒序輸出
scala> for( i<- (0 until intArrayVar.length).reverse) println("Array Element: "+
 intArrayVar(i))
Array Element: 2
Array Element: 1
Array Element: 1

4 陣列轉換

//生成新的陣列,原陣列不變
//緩衝資料轉換後產生的仍然是緩衝陣列
scala> var intArrayVar2=for(i <- intArrayVar) yield i*2
intArrayVar2: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(2, 2, 4)

//定長陣列轉轉後產生的仍然是定長陣列,原陣列不變
scala> var intArrayNoBuffer=Array(1,2,3)
intArrayNoBuffer: Array[Int] = Array(1, 2, 3)

scala> var intArrayNoBuffer2=for(i <- intArrayNoBuffer) yield i*2
intArrayNoBuffer2: Array[Int] = Array(2, 4, 6)

//加入過濾條件
scala>  var intArrayNoBuffer2=for(i <- intArrayNoBuffer if i>=2) yield i*2
intArrayNoBuffer2: Array[Int] = Array(4, 6)

5 陣列操作中的常用演算法

//定義一個整型陣列
scala> val intArr=Array(1,2,3,4,5,6,7,8,9,10)
intArr: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

//求和
scala> intArr.sum
res87: Int = 55

//求最大值
scala> intArr.max
res88: Int = 10

scala> ArrayBuffer("Hello","Hell","Hey","Happy").max
res90: String = Hey

//求最小值
scala> intArr.min
res89: Int = 1

//toString()方法
scala> intArr.toString()
res94: String = [I@141aba8

//mkString()方法
scala> intArr.mkString(",")
res96: String = 1,2,3,4,5,6,7,8,9,10

scala> intArr.mkString("<",",",">")
res97: String = <1,2,3,4,5,6,7,8,9,10>

6 ArrayBuffer Scaladoc解析

初學者在檢視sacaladoc時常常會感到困惑,不用擔心,隨著學習的深入,api文件中的內容將逐漸清晰
下面給出兩個示例:
++=方法傳入的引數型別是TraversableOnce Trait的子類,它返回的是更新好的ArrayBuffer
這裡寫圖片描述

dropWhile傳入的是一個函式,該函式返回值是布林型別,dropWhile反回的是操作後的ArrayBuffer
這裡寫圖片描述

7 多維陣列

通過陣列的陣列實現多維陣列的定義:

//定義2行3列陣列
scala> var multiDimArr=Array(Array(1,2,3),Array(2,3,4))
multiDimArr: Array[Array[Int]] = Array(Array(1, 2, 3), Array(2, 3, 4))

//獲取第一行第三列元素
scala> multiDimArr(0)(2)
res99: Int = 3

//多維陣列的遍歷
scala> for(i <- multiDimArr) println( i.mkString(","))
1,2,3
2,3,4

列表List操作實戰

1 List型別定義及List的特點

//字串型別List
scala> val fruit=List("Apple","Banana","Orange")
fruit: List[String] = List(Apple, Banana, Orange)

//前一個語句與下面語句等同
scala> val fruit=List.apply("Apple","Banana","Orange")
fruit: List[String] = List(Apple, Banana, Orange)

//數值型別List
scala> val nums=List(1,2,3,4,5)
nums: List[Int] = List(1, 2, 3, 4, 5)

//多重ListList的子元素為List
scala> val diagMatrix=List(List(1,0,0),List(0,1,0),List(0,0,1))
diagMatrix: List[List[Int]] = List(List(1, 0, 0), List(0, 1, 0), List(0, 0, 1))

//遍歷List
scala> for (i <- nums) println("List Element: "+i)
List Element: 1
List Element: 2
List Element: 3
List Element: 4
List Element: 5

不難看出,List與Array有著諸多的相似之處,但它們有兩個明顯的區別:
1 List一但建立,其值不能被改變
如前面的nums,改變其值的話,編譯器會報錯

scala> nums(3)=4
<console>:10: error: value update is not a member of List[Int]
              nums(3)=4
              ^

2 List具有遞迴結構(Recursive Structure),例如連結串列結構

List型別和其它型別集合一樣,它具有協變性(Covariant),即對於型別S和T,如果S是T的子型別,則List[S]也是List[T]的子型別

例如

scala> var listStr:List[Object]=List("This","Is","Covariant","Example")
listStr: List[Object] = List(This, Is, Covariant, Example)

//空的List,其型別為Nothing,Nothing在Scala的繼承層次中的最低層
//,即Nothing是任何Scala其它型別如String,Object等的子類
scala> var listStr=List()
listStr: List[Nothing] = List()

scala> var listStr:List[String]=List()
listStr: List[String] = List()

2 List常用構造方法

//採用::及Nil進行列表構建
scala> val nums = 1 :: (2 :: (3 :: (4 :: Nil)))
nums: List[Int] = List(1, 2, 3, 4)

//由於::操作符的優先順序是從右往左的,因此上一條語句等同於下面這條語句
scala> val nums=1::2::3::4::Nil
nums: List[Int] = List(1, 2, 3, 4)

3 List常用操作

//判斷是否為空
scala> nums.isEmpty
res108: Boolean = false

//取第一個無素
scala> nums.head
res109: Int = 1

//取除第一個元素外剩餘的元素,返回的是列表
scala> nums.tail
res114: List[Int] = List(2, 3, 4)

//取列表第二個元素
scala> nums.tail.head
res115: Int = 2

//插入排序演算法實現
def isort(xs: List[Int]): List[Int] =
if (xs.isEmpty) Nil
else insert(xs.head, isort(xs.tail))

def insert(x: Int, xs: List[Int]): List[Int] =
if (xs.isEmpty || x <= xs.head) x :: xs
else xs.head :: insert(x, xs.tail)

//List連線操作
scala> List(1,2,3):::List(4,5,6)
res116: List[Int] = List(1, 2, 3, 4, 5, 6)

//取除最後一個元素外的元素,返回的是列表
scala> nums.init
res117: List[Int] = List(1, 2, 3)

//取列表最後一個元素
scala> nums.last
res118: Int = 4

//列表元素倒置
scala> nums.reverse
res119: List[Int] = List(4, 3, 2, 1)

//一些好玩的方法呼叫
scala> nums.reverse.reverse==nums
res120: Boolean = true

scala> nums.reverse.init
res121: List[Int] = List(4, 3, 2)

scala> nums.tail.reverse
res122: List[Int] = List(4, 3, 2)

//丟棄前n個元素
scala> nums drop 3
res123: List[Int] = List(4)

scala> nums drop 1
res124: List[Int] = List(2, 3, 4)

//獲取前n個元素
scala> nums take 1
res125: List[Int] = List(1)

scala> nums.take(3)
res126: List[Int] = List(1, 2, 3)

//將列表進行分割
scala> nums.splitAt(2)
res127: (List[Int], List[Int]) = (List(1, 2),List(3, 4))

//前一個操作與下列語句等同
scala> (nums.take(2),nums.drop(2))
res128: (List[Int], List[Int]) = (List(1, 2),List(3, 4))

//Zip操作
scala> val nums=List(1,2,3,4)
nums: List[Int] = List(1, 2, 3, 4)

scala> val chars=List('1','2','3','4')
chars: List[Char] = List(1, 2, 3, 4)

//返回的是List型別的元組(Tuple)
scala> nums zip chars
res130: List[(Int, Char)] = List((1,1), (2,2), (3,3), (4,4))

//List toString方法
scala> nums.toString
res131: String = List(1, 2, 3, 4)

//List mkString方法
scala> nums.mkString
res132: String = 1234

//轉換成陣列
scala> nums.toArray
res134: Array[Int] = Array(1, 2, 3, 4)
  1. List伴生物件方法
//apply方法
scala>  List.apply(1, 2, 3)
res139: List[Int] = List(1, 2, 3)

//range方法,構建某一值範圍內的List
scala>  List.range(2, 6)
res140: List[Int] = List(2, 3, 4, 5)

//步長為2
scala>  List.range(2, 6,2)
res141: List[Int] = List(2, 4)

//步長為-1
scala>  List.range(2, 6,-1)
res142: List[Int] = List()

scala>  List.range(6,2 ,-1)
res143: List[Int] = List(6, 5, 4, 3)

//構建相同元素的List
scala> List.make(5, "hey")
res144: List[String] = List(hey, hey, hey, hey, hey)

//unzip方法
scala> List.unzip(res145)
res146: (List[Int], List[Char]) = (List(1, 2, 3, 4),List(1, 2, 3, 4))

//list.flatten,將列表平滑成第一個無素
scala> val xss =
     | List(List('a', 'b'), List('c'), List('d', 'e'))
xss: List[List[Char]] = List(List(a, b), List(c), List(d, e))
scala> xss.flatten
res147: List[Char] = List(a, b, c, d, e)

//列表連線
scala> List.concat(List('a', 'b'), List('c'))
res148: List[Char] = List(a
, b, c)

新增公眾微訊號,可以瞭解更多最新Spark、Scala相關技術資訊
這裡寫圖片描述