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.
1,2,3,4,5,6, Elements Access Using Index 1 2 3 4 5 6
Some of the Predefined Methods used in Sequence
- def apply(index: Int): A -> To select an element from the sequence
- def contains[A1 >: A](elem: A1): Boolean -> To check whether a sequence contains the given element
- def count(p: (A)=> Boolean): Int-> To count the number of elements that satisfies a predicate
- def length: Int -> gives the length of the Sequence
- def copyToArray(xs: Array[A], start: Int, len: Int): Unit -> For copying the elements of Sequence to array
- def endsWith[B](that: GenSeq[B]): Boolean-> to check whether a sequence terminates with a given sequence or not
- def head: A ->It selects the first element of the sequence.
- def indexOf(elem: A): Int-> To find the index of first occurrence of a value in the sequence
- def isEmpty: Boolean ->To test the emptiness of the sequence.
- def lastIndexOf(elem: A): Int-> To find the index of last occurrence of a value in the sequence
- def reverse: Seq[A]-> To return a new sequence with elements in reverse order.
Sequence Example using Predefined methods
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)