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::,發音為cons。Nil 也表示空列表。所有上述列表都可以按如下方式定義。

// 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中。以下命令用於編譯和執行此程式。

命令

\>scalac Demo.scala
\>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中。以下命令用於編譯和執行此程式。

命令

\>scalac Demo.scala
\>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中。以下命令用於編譯和執行此程式。

命令

\>scalac Demo.scala
\>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中。以下命令用於編譯和執行此程式。

命令

\>scalac Demo.scala
\>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中。以下命令用於編譯和執行此程式。

命令

\>scalac Demo.scala
\>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

將列表的元素複製到陣列。用此列表的最多 length (len) 個元素填充給定的陣列 xs,從位置 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]

根據 Ordering 對列表進行排序。

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_collections.htm
廣告