Thursday 19 May 2016

Scala Useful Code Snippets for Beginners(Part-4): Seq

Introduction

In Scala, Seq(Sequence) is a one kind of Iterable. The major difference between Iterable and Seq is that sequences always have a defined order of elements.

It has the following 3 flavours in Scala API:
  1. scala.collection.Seq
  2. scala.collection.mutable.Seq
  3. scala.collection.immutable.Seq
Based on context, we can use either Mutable or Immutable Seq.


Just like Strings uses '+' operator for String concatenation,  Seq uses '++' function( But Not an operator) to concatenate two Sequences.

Seq uses '+' function( But Not an operator) to add a new element at the end of the existing Sequence. 

NOTE:- If we don't specify the type of Seq, Scala Compiler creates Immutable Seq automatically.

Let us explore Scala Seq with some examples.

Examples:

To create empty Seq

scala> val seq1 = Seq()

seq1: Seq[Nothing] = List()

To Concatenate Two Sequences using "++"

scala> val seq2 = Seq(1,2,3)
seq2: Seq[Int] = List(1, 2, 3)

scala> val seq3 = Seq(4,5)
seq3: Seq[Int] = List(4, 5)

scala> val seq4 = seq2 ++ seq3
seq4: Seq[Int] = List(1, 2, 3, 4, 5)


To access Sequence elements using index

scala> seq4
res1: Seq[Int] = List(1, 2, 3, 4, 5)

scala> seq4(0)
res2: Int = 1

scala> seq4(1)
res3: Int = 2

NOTE:- Seq index starts with zero.

To reverse the Seq elements

scala> seq4.reverse
res7: Seq[Int] = List(5, 4, 3, 2, 1)

To use Seq's slice function

scala> seq4.slice(0,2)
res8: Seq[Int] = List(1, 2)

scala> seq4.slice(1,2)
res9: Seq[Int] = List(2)

scala> seq4.slice(1,3)
res10: Seq[Int] = List(2, 3)

NOTE:- slice function returns all elements from first element index until second element index 

from <= indexOf(first-parameter) < second-parameter

Some useful Seq functions

scala> seq4.mkString
res4: String = 12345

scala> seq4.foreach(print)
12345
scala> seq4.foreach(println)
1
2
3
4
5


Thank you for reading my posts. 
Please drop me your valuable suggestions or comments.

No comments:

Post a Comment