Scala Collections - Seq


Advertisements

Scala Seq is a trait to represent immutable sequences. This structure provides index based access and various utility methods to find elements, their occurences and subsequences. A Seq maintains the insertion order.

Declaring Seq Variables

The following is the syntax for declaring an Seq variable.

Syntax

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

Here, seq is declared as an Seq of numbers. Seq provides commands like the following −

Command

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

Processing Seq

Below is an example program of showing how to create, initialize and process Seq −

Example

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)           
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

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)
Advertisements