Open In App

Scala Sequence

Sequence is an iterable collection of class Iterable. It is used to represent indexed sequences that are having a defined order of element i.e. guaranteed immutable. The elements of sequences can be accessed using their indexes. Method apply is used for the purpose of indexing. Sequences can also be accessed reversibly using the method reverse and reverseIterator. 
The indices range from 0 to (n – 1) Where, n= the length of the sequence. For the purpose of finding the subsequences, sequences support various methods. Methods such as indexOf, segmentLength, prefixLength, lastIndexWhere, lastIndexOf, startsWith, endsWith. There are two primary subtraits of Sequence namely IndexedSeq and LinearSeq which gives different performance guarantees. IndexexedSeq provides fast and random access of elements while LinearSeq provides fast access to the first element only via head and also contains a fast tail operation. 
Example #1: 
 




// Scala program to illustrate sequence
import scala.collection.immutable._
 
object GFG
{
    // Main Method
    def main(args:Array[String])
    {
        // Initializing sequence
        var seq:Seq[Int] = Seq(1,2,3,4,5,6)
         
        // Printing Sequence
        seq.foreach((element:Int) => print(element+","))
        println("\nElements Access Using Index")
        println(seq(0))
        println(seq(1))
        println(seq(2))
        println(seq(3))
        println(seq(4))
        println(seq(5))
    }
}

Output

1,2,3,4,5,6,
Elements Access Using Index
1
2
3
4
5
6

Some of the Predefined Methods used in Sequence 
 

Sequence Example using Predefined methods 
Example #2: 
 






// Scala program to illustrate sequence
object MainObject
{
    // Main Method
    def main(args:Array[String])
    {
        // Initializing sequence
        var seq:Seq[Int] = Seq(1, 2, 3, 4, 5, 6)
         
        // Printing Sequence
        seq.foreach((element:Int) => print(element+","))
         
        // Using Some Predefined Methods
        println("\nis Empty: "+ seq.isEmpty)
        println("\nEnds with (5,6): "+ seq.endsWith(Seq(5,6)))
        println("\nLength of sequence: "+ seq.length)
        println("\ncontains 3: "+ seq.contains(3))
        println("\nlast index of 4 : "+ seq.lastIndexOf(4))
        println("\nReversed sequence: "+ seq.reverse)
    }
}

Output
1,2,3,4,5,6,
is Empty: false

Ends with (5,6): true

Length of sequence: 6

contains 3: true

last index of 4 : 3

Reversed sequence: List(6, 5, 4, 3, 2, 1)

Article Tags :