Scala列表

Scala列表與數組非常相似,列表的所有元素都具有相同的類型,但有兩個重要的區別。 首先,列表是不可變的,列表的元素不能通過賦值來更改。 其次,列表表示一個鏈表,而數組是平的。

具有類型T的元素的列表的類型被寫為List[T]

嘗試以下示例,這裏列出了為各種數據類型定義的列表。

// List of Strings
val fruit: List[String] = List("apples", "oranges", "pears")

// List of Integers
val nums: List[Int] = List(1, 2, 3, 4)

// Empty List.
val empty: List[Nothing] = List()

// Two dimensional list
val dim: List[List[Int]] =
   List(
      List(1, 0, 0),
      List(0, 1, 0),
      List(0, 0, 1)
   )

所有列表都可以使用兩個基本構建塊定義,尾部為Nil::,它的發音為consNil也代表空列表。以上列表可以定義如下。

// List of Strings
val fruit = "apples"::("oranges"::("pears"::Nil))

// List of Integers
val nums = 1::(2::(3::(4::Nil)))

// Empty List.
val empty = Nil

// Two dimensional list
val dim = (1::(0::(0::Nil))) ::
          (0::(1::(0::Nil))) ::
          (0::(0::(1::Nil)))::Nil

列表基本操作

列表上的所有操作都可以用以下三種方法表示。

序號 方法 描述
1 head 此方法返回列表的第一個元素。
2 tail 此方法返回由除第一個之外的所有元素組成的列表。
3 isEmpty 如果列表為空,則此方法返回true,否則返回false

以下示例顯示如何使用上述方法。

示例

object Demo {
   def main(args: Array[String]) {
      val fruit = "apples"::("oranges"::("pears"::Nil))
      val nums = Nil

      println( "Head of fruit : " + fruit.head )
      println( "Tail of fruit : " + fruit.tail )
      println( "Check if fruit is empty : " + fruit.isEmpty )
      println( "Check if nums is empty : " + nums.isEmpty )
   }
}

將上述程式保存在原始檔案:Demo.scala中,使用以下命令編譯和執行此程式。

D:\>scalac Demo.scala
D:\>scala Demo

Head of fruit : apples
Tail of fruit : List(oranges, pears)
Check if fruit is empty : false
Check if nums is empty : true

連接列表

可以使用:::操作符或List.:::()方法或List.concat()方法添加兩個或多個列表。 請看下麵給出的例子 -

示例

object Demo {
   def main(args: Array[String]) {
      val fruit1 = "apples"::("oranges"::("pears"::Nil))
      val fruit2 = "mangoes"::("banana"::Nil)

      // use two or more lists with ::: operator
      var fruit = fruit1 ::: fruit2
      println( "fruit1 ::: fruit2 : " + fruit )

      // use two lists with Set.:::() method
      fruit = fruit1.:::(fruit2)
      println( "fruit1.:::(fruit2) : " + fruit )

      // pass two or more lists as arguments
      fruit = List.concat(fruit1, fruit2)
      println( "List.concat(fruit1, fruit2) : " + fruit  )
   }
}

將上述程式保存在原始檔案:Demo.scala中,使用以下命令編譯和執行此程式。

D:\>scalac Demo.scala
D:\>scala Demo

fruit1 ::: fruit2 : List(apples, oranges, pears, mangoes, banana)
fruit1.:::(fruit2) : List(mangoes, banana, apples, oranges, pears)
List.concat(fruit1, fruit2) : List(apples, oranges, pears, mangoes, banana)

創建統一列表

可以使用List.fill()方法創建由零個或多個相同元素的副本組成的列表。 請嘗試以下示例程式。

示例

object Demo {
   def main(args: Array[String]) {
      val fruit = List.fill(3)("apples") // Repeats apples three times.
      println( "fruit : " + fruit  )

      val num = List.fill(10)(2)         // Repeats 2, 10 times.
      println( "num : " + num  )
   }
}

將上述程式保存在原始檔案:Demo.scala中,使用以下命令編譯和執行此程式。

D:\>scalac Demo.scala
D:\>scala Demo

fruit : List(apples, apples, apples)
num : List(2, 2, 2, 2, 2, 2, 2, 2, 2, 2)

製錶函數

您可以使用一個函數與List.tabulate()方法在列表之前應用於列表的所有元素。它的參數與List.fill類似:第一個參數列表給出要創建的列表的維度,第二個參數列出了列表的元素。唯一的區別是,它不修復元素,而是從函數中計算。

請嘗試以下示例程式 -

object Demo {
   def main(args: Array[String]) {
      // Creates 5 elements using the given function.
      val squares = List.tabulate(6)(n => n * n)
      println( "squares : " + squares  )

      val mul = List.tabulate( 4,5 )( _ * _ )
      println( "mul : " + mul  )
   }
}

將上述程式保存在原始檔案:Demo.scala中,使用以下命令編譯和執行此程式。

D:\>scalac Demo.scala
D:\>scala Demo

squares : List(0, 1, 4, 9, 16, 25)
mul : List(List(0, 0, 0, 0, 0), List(0, 1, 2, 3, 4),
   List(0, 2, 4, 6, 8), List(0, 3, 6, 9, 12))

反向列表順序

可以使用List.reverse方法來反轉列表的所有元素。以下示例顯示了使用情況 -

object Demo {
   def main(args: Array[String]) {
      val fruit = "apples"::("oranges"::("pears"::Nil))

      println( "Before reverse fruit : " + fruit )
      println( "After reverse fruit : " + fruit.reverse )
   }
}

將上述程式保存在原始檔案:Demo.scala中,使用以下命令編譯和執行此程式。

D:\>scalac Demo.scala
D:\>scala Demo

Before reverse fruit : List(apples, oranges, pears)
After reverse fruit : List(pears, oranges, apples)

Scala列表方法

以下是使用列表時可以使用的重要方法。有關可用方法的完整列表,請查看Scala的官方文檔。

序號 方法 描述
1 def +(elem: A): List[A] 向列表中添加一個元素
2 def ::(x: A): List[A] 向列表開頭位置添加一具元素。
3 def :::(prefix: List[A]): List[A] 在此列表前添加給定列表中的元素。
4 def ::(x: A): List[A] 在列表的開頭添加一個元素x
5 def addString(b: StringBuilder): StringBuilder 將列表的所有元素附加到字串構建器。
6 def addString(b: StringBuilder, sep: String): StringBuilder 使用分隔符號字串將列表的所有元素附加到字串構建器。
7 def apply(n: Int): A 通過列表中的索引選擇一個元素。
8 def contains(elem: Any): Boolean 測試列表是否包含給定元素值。
9 def copyToArray(xs: Array[A], start: Int, len: Int): Unit 將列表的元素複製到數組。在給定的數組xs中填充該列表的最多為長度(len)元素,從start位置開始。
10 def distinct: List[A] 從列表中創建一個新的列表,而不會有任何重複的元素。
11 def drop(n: Int): List[A] 返回除了前n個之外的所有元素。
12 def dropRight(n: Int): List[A] 返回除最後n個之外的所有元素。
13 def dropWhile(p: (A) => Boolean): List[A] 刪除滿足謂詞的元素的最長首碼。
14 def endsWith[B](that: Seq[B]): Boolean 測試列表是否以給定的順序結束。
15 def equals(that: Any): Boolean 任意序列的equals方法,將此序列與其他對象進行比較。
16 def exists(p: (A) => Boolean): Boolean 測試一個謂詞是否適用於列表的某些元素。
17 def filter(p: (A) => Boolean): List[A] 返回列表中滿足謂詞的所有元素。
18 def forall(p: (A) => Boolean): Boolean 測試列表中所有元素的謂詞是否成立。
19 def foreach(f: (A) => Unit): Unit 將函數f應用於列表的所有元素。
20 def head: A 選擇列表的第一個元素。
21 def indexOf(elem: A, from: Int): Int 在索引位置之後,查找列表中第一個出現值的索引。
22 def init: List[A] 返回除上一個以外的所有元素。
23 def intersect(that: Seq[A]): List[A] 計算列表和另一個序列之間的多集合交集。
24 def isEmpty: Boolean 測試列表是否為空。
25 def iterator: Iterator[A] 在可迭代對象中包含的所有元素上創建一個新的迭代器。
26 def last: A 返回最後一個元素。
27 def lastIndexOf(elem: A, end: Int): Int 查找列表中某些值的最後一次出現的索引; 在給定的結束指數之前或之中。
28 def length: Int 返回列表的長度。
29 def map[B](f: (A) => B): List[B] 通過將函數應用於此列表的所有元素來構建新集合。
30 def max: A 查找最大元素。
31 def min: A 查找最小元素。
32 def mkString: String 顯示字串中列表的所有元素。
33 def mkString(sep: String): String 使用分隔符號字串顯示字串中列表的所有元素。
34 def reverse: List[A] 以相反的順序返回帶有元素的新列表。
35 def sorted[B >: A]: List[A] 根據順序規則對列表進行排序。
36 def startsWith[B](that: Seq[B], offset: Int): Boolean 測試列表是否包含給定索引處的給定序列。
37 def sum: A 將這個集合所有元素相加。
38 def tail: List[A] 返回除第一個之外的所有元素。
39 def take(n: Int): List[A] 返回第一個“n”個元素。
40 def takeRight(n: Int): List[A] 返回最後的“n”個元素。
41 def toArray: Array[A] 將列表轉換為數組。
42 def toBuffer[B >: A]: Buffer[B] 將列表轉換為可變緩衝區。
43 def toMap[T, U]: Map[T, U] 將此列表轉換為映射。
44 def toSeq: Seq[A] 將列表轉換為序列。
45 def toSet[B >: A]: Set[B] 將列表轉換為一個集合。
46 def toString(): String 將列表轉換為字串。

上一篇: Scala集合 下一篇: Scala模式匹配