SCALA COLLECTIONS

SCALA COLLECTIONS :




List :

Scala Lists are similar to Arrays which means that all elements of a list have the same type but there are two important differences. First Lists are immutable (Cannot be changed) and Second Lists are represented, Linked List.

scala > val names : List [String] = List (“Sreekanth”, “Vijay”, “Vinay”);

names : List[String] = List (Sreekanth, Vijay, Vinay)

scala > val names : List[String] = List (“Alien”, “Bob”, “Carey”);

names: List [String] = List (Alien, Bob, Carey)

scala > println(names (0));

O/P : Alien

scala > println (names (1));

O/P : Bob

scala > val marks = List[Int] = List [10,20,30,40)

marks: List[Int] = List(10,20,30,40)

scala > prinltn(marks. head)

O/P : 10

scala > prinltn (marks. tail)

O/P : 20,30,40

To Concatenate the Two Lists using :::

val names  = “Sreekanth” :: ( “Vijay”:: “Vinay”);

names: List [String] = List (Sreekanth, Vijay, Vinay)

val address = “Hyd” :: (“Banglore” :: (“Chennai” ))

address: List[String] = List (Hyd, Banglore, Chennai)

var name_address= names ::: address

name_address: List [String] = List (Sreekanth, Vijay, Vinay, Hyd, Banglore, Chennai)

Set :

Set is a collection that contains no duplicate elements. There are two kinds of Sets, the immutable and mutable. The difference between mutable and immutable objects that when an object is immutable the object itself can’t be changed.

By default, Scala uses the immutable set.

Scala > val ranks = List (1,2,3,4,2,2,3,2)

ranks: List[Int] = List (1,2,3,4,2,2,3,2)

Scala > val ranks = Set(1,2,3,4,2,2,3,2)

ranks : scala .collection.immutable.Set[Int] = Set (1,2,3,4)




Set Operations in Scala:

Example : object setOperations

{

def main (args: Array[String])

{

val marks = Set(10,20,30,40);

val updateMarks = set(15,25,35,45);

println (“Max marks : ” + marks .max);

prinltn( “Min marks :” + marks.min);

prinltn (“marks.intersect(updateMarks): ” + marks.intersect(updateMarks));

}

}

 

 Maps:

  1. Scala map is a collection of key and value pairs in a collection set.
  2. Any value can be retrieved based on its key.
  3. Keys are unique in the Map, but values need not be unique.
  4. There are two kinds of Maps, the immutable and the mutable.

scala > mapPrgogram.scala

object mapPrg

{

def main(args: Array[String])

{

val Technology= Map (“Java” -> “OOPS”, “ML” -> AI , “Hadoop” -> “Big Data”);

println(“Keys in Technologies:” + Technology.keys);

prinltn(“Values of Technologies:” + Technology.values)

}

}

scala > scalac mapProgram.scala

scala > scala mapProgram

Output:

Keys in Technologies: Set(Java, ML, Hadoop)

Values in Technologies : Map ( OOPS, AI, Big Data )

Leave a Reply

Your email address will not be published. Required fields are marked *