bing
Flat 10% & upto 50% off + Free additional Courses. Hurry up!

Scala Collections

 

Collections are the container of things which contains random number of elements. All collection classes are found in the package scala.collection. Collections are of two types –

  • Mutable Collections
  • Immutable Collections

Mutable Collection – This type of collection is changed after it is created. All Mutable collection classes are found in the package scala.collection.mutable.

Immutable Collection – This type of collection will never change after it is created. All Immutable collection classes are found in the package scala.collection.immutable.

 

Most Common Collection types are –

  1. List
  2. Map
  3. Set
  4. Tuple
  5. Iterators

 

1. List – List is a collection of similar types of elements which are immutable. It represents the Linked list. If list contains t tpes of elements then it can be represented as –

List[t]

The empty list is specified by Nil which is an object that represents any empty list. The method :: pronounced cons transforms an object and a list into a new list whose head is the object and whose tail is the first list.

val numbers: List[Int] = List(10, 20, 30 ,40)  //List of Integers

val empty: List[Int] = List()  // Empty List

val twodim: List[List[Int]] =

List (

List (0, 1, 0),

List (1, 1, 0)

)

 

List Constructors – All lists are built from two more fundamental constructors that is Nil and :: .Nil represents an empty list. The infix operator :: expresses list extension. That is, x :: xs represents a list whose first element is x, which is followed by list xs. You can also define the list as follows:

val numbers = 10 :: (20 :: (30 :: (40 :: Nil)))

val empty = Nil

val twodim = (0 :: (1 :: (0 :: Nil))) ::

(1 :: (1 :: (0 :: Nil))) :: Nil

For simplicity you can definje above list as follows:-

val numbers = 10 :: 20 :: 30 :: 40 :: Nil

 

Basic operations on lists –

Methods Description
head It returns the first element of a list.
tail It returns a list consisting of all elements except the first.
isEmpty It returns true if the list is empty.

e.g.

object Intellipaat {

def main(args: Array[String]) {

val numbers = 10 :: (20 :: (30 :: (40 :: Nil)))

val data = Nil

println( "Head of Number is : " + numbers.head )

println( "Tail of Number is : " + numebrs.tail )

println( "Check number is empty or not : " + numbers.isEmpty )

println( "Check data is empty or not : " + data.isEmpty )

}

}

Compile and execute the above program:

scalac Intellipaat.scala

scala Intellipaat

Output:

Head of Number is : 10

Tail of Number is : List(20, 30, 40)

Check number is empty or not :False

Check data is empty or not : True

 

  • List.concat() –  It is used to perform concatenation of two lists.
  • List.fill() – It creates a lsit which contains same element.
  • List.tabulate() – It converts the list in tabular form.
  • List.reverse – It is used to reverse the list elements.

 

2. Map (Hash Table) – It is a collection of key/value pairs where key are unique and value is retrieved according to the key. Scala Online Training provides mutable and immutable versions of Map. If you want to use immutable map then use Map and if you want to use mutable map the use mutable.Map.

 

class hierarchy for scala map

 

e.g.

var I:Map[String ,Int] = Map()  // Creates empty hash table whose values are integers and keys are string type

val data = Map(

‘a’ ->10,

‘b’ -> 20,

‘c’->30,

‘d’ ->40

)

 

Basic Operations on Map:

All operations on maps can be expressed in terms of the following three methods:

Methods Description
keys It returns an iterable containing each key in the map.
values It returns an iterable containing each value in the map.
isEmpty It returns true if the map is empty otherwise false.

e.g.

object Intellipaat {

def main(args: Array[String]) {

val numbers = Map(

‘a’ ->10, ‘b’ -> 20, ‘c’->30, ‘d’ ->40

)

val data: Map[char, Int] = Map()

println( "Keys in Numbers are : " + numbers.keys )

println( "Values in numbers are : " + numbers.values )

println( "Check number is empty or not : " + numbers.isEmpty )

println( "Check data is empty or not : " + data.isEmpty )

}

}

Compile and execute the above program:

scalac Intellipaat.scala

scala Intellipaat

Output :

Keys in Numbers are : Set(a, b, c, d)

Values in numbers are : MapLike (10, 20, 30, 40)

Check number is empty or not :False

Check data is empty or not : True

 

  • Map.++() – It is used to concatenate two or more maps.
  • Map.contains – It checks that if a given key exists in the map or not.
  • Foreach loop – It is used to print the keys and values of map.

 

3. Set – It is a collection of elements which are of same type but does not contain same elements. By default scala uses immutable set. Scala provides mutable and immutable versions of Set. If you want to use immutable set then use Set and if you want to use mutable set the use mutable.Set.

 

class hierarchy for scala set

 

var i : Set[Int] = Set()    // Empty set of integer type

var i : Set[Int] = Set(10, 20, 30, 40)  // Set of integer type

 

Basic Operations on Set:

All operations on sets can be expressed in terms of the following three methods:

Methods Description
head It returns the first element of a set.
tail It returns a set consisting of all elements except the first.
isEmpty It returns true if the set is empty otherwise false.

e.g.

object Intellipaat {

def main(args: Array[String]) {

val numbers = Set(10, 20, 30, 40)

val data: Set[Int] = Set()

println( "Head of Number is : " + numbers.head )

println( "Tail of numbers is : " + numbers.tail )

println( "Check number is empty or not : " + numbers.isEmpty )

println( "Check data is empty or not : " + data.isEmpty )

}

}

Compile and execute the above program:

scalac Intellipaat.scala

scala Intellipaat

Output:

Head of Number is : 10

Tail of Number is : Set(20, 30, 40)

Check number is empty or not :False

Check data is empty or not : True

 

  • Set.++() – It is used to concatenate the two or more sets.
  • Set.min – It is used to find the minimum value from the elements of the set.
  • Set.max() – It is used to find the maximum value from the elements of the set.
  • Set.intersect – It is used to find the common values between two sets.
  • Set.& – It is also used to find the common values between two sets.

 

4. Tuples – It is a collection of heterogeneous types of objects that is different types of objects which combines a fixed number of items together.

 

Tuple that contains an Int and a String:

val i = (1, "intellipaat")

To access tuple elements ‘._’ is used.

e.g.

object Intellipaat {

def main(args: Array[String]) {

val i = (10, 20, 30, 40)

val total = i._1 + i._2 + i._3 + i._4

println( "Total of Elements is : "  + total)

}

}

Compile and execute the above program:

scalac Intellipaat.scala

scala Intellipaat

Output

Total of elements is : 100

  • Tuple.productIterator() – It is used to iterate over all the elements of a Tuple.
  • Tuple.toString() – It is used to concatenate all the elements of the tuple into a string.
  • Tuple.swap – It is used to swap the elements of a Tuple.

 

5. Iterator – It is used to access the elements of the collection one by one.Two important operations of iterator is –

  • next
  • hasNext

next – It is used to return the next element of the iterator and move ahead the state of the iterator.

hasNext – It is used to find out whether there are more elements to return.

 

e.g.

object Intellipaat {

def main(args: Array[String]) {

val i = Iterator("hello", "intellipaat", "a", "ecommerce", “site”)

while (i.hasNext){

println(i.next())

}

}

}

Compile and execute the above program:

scalac Intellipaat.scala

scala Intellipaat

 Output

hello

intellipaat

a

ecommerce

site

 

  • iterartor.min – It is used to return the minimum value elements form iterator.
  • iterator.max – It is used to return the maximum value elements form iterator.
  • iterator.size – It is used to return the number of element of elements in iterator.
  • iterator.length – It is also used to return the number of element of elements in iterator.

"0 Responses on Scala Collections"

Training in Cities

Bangalore, Hyderabad, Chennai, Delhi, Kolkata, UK, London, Chicago, San Francisco, Dallas, Washington, New York, Orlando, Boston

100% Secure Payments. All major credit & debit cards accepted Or Pay by Paypal.

top

Sales Offer

  • To avail this offer, enroll before 04th December 2016.
  • This offer cannot be combined with any other offer.
  • This offer is valid on selected courses only.
  • Please use coupon codes mentioned below to avail the offer
offer-june

Sign Up or Login to view the Free Scala Collections.