Scala 集合 - Seq



Scala Seq 是一個用於表示不可變序列的特徵。這種結構提供了基於索引的訪問以及各種實用程式方法來查詢元素、它們的出現次數和子序列。Seq 保持插入順序。

宣告 Seq 變數

以下是宣告 Seq 變數的語法。

語法

val seq: Seq[Int] = Seq(1, 2, 3, 4, 5)

這裡,seq 被宣告為一個數字的 Seq。Seq 提供了以下命令:

命令

val isPresent = seq.contains(4);
val contains = seq.endsWith(Seq(4,5));
var lastIndexOf = seq.lasIndexOf(5);

處理 Seq

下面是一個示例程式,展示瞭如何建立、初始化和處理 Seq:

示例

import scala.collection.immutable.Seq
object Demo {
   def main(args: Array[String]) = {
      var seq = Seq(1, 2, 3, 4, 5, 3)
      // Print seq elements
      seq.foreach{(element:Int) => print(element + " ")}
      println()
      println("Seq ends with (5,3): " + seq.endsWith(Seq(5, 3)))
      println("Seq contains 4: " + seq.contains(4))
      println("Last index of 3: " + seq.lastIndexOf(3))
      println("Reversed Seq" + seq.reverse)           
   }
}

將上述程式儲存在 Demo.scala 中。以下命令用於編譯和執行此程式。

命令

\>scalac Demo.scala
\>scala Demo

輸出

1 2 3 4 5 3
Seq ends with (5,3): true
Seq contains 4: true
Last index of 3: 5
Reversed SeqList(3, 5, 4, 3, 2, 1)
廣告

© . All rights reserved.