Sunday, 12 May 2019

Seq in Scala

Seq

A base trait for sequences.
Sequences are special cases of iterable collections of class Iterable. Unlike iterables, sequences always have a defined order of elements. Sequences provide a method apply for indexing. Indices range from 0 up to the length of a sequence. Sequences support a number of methods to find occurrences of elements or subsequences, including segmentLength, prefixLength, indexWhere, indexOf, lastIndexWhere, lastIndexOf, startsWith, endsWith, indexOfSlice.
Another way to see a sequence is as a PartialFunction from Int values to the element type of the sequence. The isDefinedAt method of a sequence returns true for the interval from 0 until length.
Sequences can be accessed in reverse order of their elements, using methods reverse and reverseIterator.
Sequences have two principal subtraits, IndexedSeq and LinearSeq, which give different guarantees for performance. An IndexedSeq provides fast random-access of elements and a fast length operation. A LinearSeq provides fast access only to the first element via head, but also has a fast tail operation.

//Code Example :
object seq {
  def main(args:Array[String]): Unit ={
    var seq:Seq[Int] = Seq(52,85,1,8,3,2,7,3,55,6,45,3,2,3,4,6,7,9)
    seq.foreach((element:Int) => print(element+", "))
    println()
    println("Sequence is empty : "+seq.isEmpty)
    println("Sequence ends with : "+seq.endsWith(Seq(6,7,19)))
    println("Sequence ends with : "+seq.endsWith(Seq(6,7,9)))
    println("Sequence contains 8 : "+seq.contains(8))
    println("Last index of 3 in sequence : "+seq.lastIndexOf(3))
    println("Index of 3 in sequence : "+seq.indexOf(3))
    println("Reverse of sequence is : "+seq.reverse)
  }
}
//Output
52, 85, 1, 8, 3, 2, 7, 3, 55, 6, 45, 3, 2, 3, 4, 6, 7, 9,
Sequence is empty : false
Sequence ends with : false
Sequence ends with : true
Sequence contains 8 : true
Last index of 3 in sequence : 13
Index of 3 in sequence : 4
Reverse of sequence is : List(9, 7, 6, 4, 3, 2, 3, 45, 6, 55, 3, 7, 2, 3, 8, 1, 85, 52)

No comments:

Post a Comment

Use filter method to filter a Scala collection

Use filter method to filter a Scala collection To use filter on your collection, give it a predicate to filter the collection elements as...