Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2020-10-08 14:24:29 Viewed : 6316
Scala Collections – Seq
def
apply[A](elems: A*): Seq[A]
Creates a collection with the specified elements
Syntax:
object Seq extends SeqFactory[Seq] {
}
Following example illustrates about Scala Seq
Save the file as − SeqExample.scala
package runnerdev
object SeqExample extends App {
var seq: Seq[Int] = Seq(1, 2, 3, 4, 5, 6, 7)
seq.foreach((element: Int) => print(element + " "))
println("
is Empty: " + seq.isEmpty)
println("Ends with (2,7): " + seq.endsWith(Seq(2, 7)))
println("contains 3: " + seq.contains(3))
println("last index of 3 : " + seq.lastIndexOf(3)) //2
println("Reverse order of sequence: " + seq.reverse)
}
scala> scalac SeqExample.scala
scala> scala SeqExample
Output:
1 2 3 4 5 6 7
is Empty: false
Ends with (2,7): false
contains
3: true
last index of 3 : 2
Reverse order of sequence: List(7, 6, 5, 4, 3, 2, 1)
In Scala, a Seq
(short for "sequence") is a common trait in the collections hierarchy. It represents an ordered sequence of elements where duplicate elements are allowed. Seq
is a more general collection type compared to List
, as it encompasses various types of sequences, including lists, arrays, and other sequence-like data structures. Here is an overview of Seq
and how to use it:
1. Creating a Seq:
You can create a Seq
in Scala using various methods:
Using Seq()
constructor:
scalaval seq1: Seq[Int] = Seq(1, 2, 3, 4, 5)
Using the List
constructor (a specific subtype of Seq
):
scalaval seq2: Seq[Int] = List(1, 2, 3, 4, 5)
Using Seq.apply
method:
scalaval seq3: Seq[Int] = Seq.apply(1, 2, 3, 4, 5)
2. Accessing Elements:
You can access elements in a Seq
using indexing (zero-based) just like you do with arrays or lists:
scalaval firstElement = seq1(0) // Access the first element (1)
3. Common Operations:
Seq
supports various common operations, including:
Concatenation:
scalaval combinedSeq = seq1 ++ Seq(6, 7, 8)
Mapping Elements:
scalaval squaredSeq = seq1.map(x => x * x)
Filtering Elements:
scalaval evenNumbers = seq1.filter(_ % 2 == 0)
Sorting Elements:
scalaval sortedSeq = seq1.sorted
4. Immutability:
Seq
is an immutable collection, meaning you cannot modify its elements once created. Instead, you create new sequences when performing operations.
5. Pattern Matching:
You can use pattern matching to destructure and process elements in a Seq
:
scalaseq1 match { case head +: tail => println(s"Head: $head, Tail: $tail") case Nil => println("Empty sequence") }
In this example, we pattern match to extract the head and tail of the sequence or handle an empty sequence.
Seq
is a versatile collection that provides an ordered sequence of elements with a wide range of operations. It is suitable for various use cases where you need to work with ordered collections of data.