Scala Collections - Quick Guide


Advertisements

Scala Collections - Overview

Scala has a rich set of collection library. Collections are containers of things. Those containers can be sequenced, linear sets of items like List, Tuple, Option, Map, etc. The collections may have an arbitrary number of elements or be bounded to zero or one element (e.g., Option).

Collections may be strict or lazy. Lazy collections have elements that may not consume memory until they are accessed, like Ranges. Additionally, collections may be mutable (the contents of the reference can change) or immutable (the thing that a reference refers to is never changed). Note that immutable collections may contain mutable items.

For some problems, mutable collections work better, and for others, immutable collections work better. When in doubt, it is better to start with an immutable collection and change it later if you need mutable ones.

This chapter throws light on the most commonly used collection types and most frequently used operations over those collections.

Sr.No Collections with Description
1

Scala Lists

Scala's List[T] is a linked list of type T.

2

Scala Sets

A set is a collection of pairwise different elements of the same type.

3

Scala Maps

A Map is a collection of key/value pairs. Any value can be retrieved based on its key.

4

Scala Tuples

Unlike an array or list, a tuple can hold objects with different types.

5

Scala Options

Option[T] provides a container for zero or one element of a given type.

6

Scala Iterators

An iterator is not a collection, but rather a way to access the elements of a collection one by one.

Scala Collections - Environment Setup

Scala can be installed on any UNIX flavored or Windows based system. Before you start installing Scala on your machine, you must have Java 1.8 or greater installed on your computer.

Follow the steps given below to install Scala.

Step 1: Verify Your Java Installation

First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the following two commands depending on the platform you are working on.

If the Java installation has been done properly, then it will display the current version and specification of your Java installation. A sample output is given in the following table.

Platform Command Sample Output
Windows

Open Command Console and type −

\>java -version

Java version "1.8.0_31"

Java (TM) SE Run Time

Environment (build 1.8.0_31-b31)

Java Hotspot (TM) 64-bit Server

VM (build 25.31-b07, mixed mode)

Linux

Open Command terminal and type −

$java -version

Java version "1.8.0_31"

Open JDK Runtime Environment (rhel-2.8.10.4.el6_4-x86_64)

Open JDK 64-Bit Server VM (build 25.31-b07, mixed mode)

We assume that the readers of this tutorial have Java SDK version 1.8.0_31 installed on their system.

In case you do not have Java SDK, download its current version from https://www.oracle.com/technetwork/java/javase/downloads/index.html and install it.

Step 2: Set Your Java Environment

Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example,

Sr.No Platform & Description
1

Windows

Set JAVA_HOME to C:\ProgramFiles\java\jdk1.8.0_31

2

Linux

Export JAVA_HOME=/usr/local/java-current

Append the full path of Java compiler location to the System Path.

Sr.No Platform & Description
1

Windows

Append the String "C:\Program Files\Java\jdk1.8.0_31\bin" to the end of the system variable PATH.

2

Linux

Export PATH=$PATH:$JAVA_HOME/bin/

Execute the command java -version from the command prompt as explained above.

Step 3: Install Scala

You can download Scala from www.scala-lang.org/downloads. At the time of writing this tutorial, I downloaded 'scala-2.13.1-installer.jar'. Make sure you have admin privilege to proceed. Now, execute the following command at the command prompt −

Platform Command & Output Description
Windows

\>java -jar scala-2.13.1-installer.jar\>

This command will display an installation wizard, which will guide you to install Scala on your windows machine. During installation, it will ask for license agreement, simply accept it and further it will ask a path where Scala will be installed. I selected default given path "C:\Program Files\Scala", you can select a suitable path as per your convenience.

Linux

Command

$java -jar scala-2.13.1-installer.jar

Output

Welcome to the installation of Scala 2.13.1!

The homepage is at − http://Scala-lang.org/

press 1 to continue, 2 to quit, 3 to redisplay

1................................................

[ Starting to unpack ]

[ Processing package: Software Package Installation (1/1) ]

[ Unpacking finished ]

[ Console installation done ]

During installation, it will ask for license agreement, to accept it type 1 and it will ask a path where Scala will be installed. I entered /usr/local/share, you can select a suitable path as per your convenience.

Finally, open a new command prompt and type Scala -version and press Enter. You should see the following −

Platform Command Output
Windows

\>scala -version

Scala code runner version 2.13.1 -- Copyright 2002-2019, LAMP/EPFL and Lightbend, Inc.

Linux

$scala -version

Scala code runner version 2.13.1 -- Copyright 2002-2019, LAMP/EPFL and Lightbend, Inc.tut

Scala Collections - Array

Scala provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables. The index of the first element of an array is the number zero and the index of the last element is the total number of elements minus one.

Declaring Array Variables

To use an array in a program, you must declare a variable to reference the array and you must specify the type of array the variable can reference.

The following is the syntax for declaring an array variable.

Syntax

var z:Array[String] = new Array[String](3)

or

var z = new Array[String](3)

Here, z is declared as an array of Strings that may hold up to three elements. Values can be assigned to individual elements or get access to individual elements, it can be done by using commands like the following −

Command

z(0) = "Zara"; z(1) = "Nuha"; z(4/2) = "Ayan"

Here, the last example shows that in general the index can be any expression that yields a whole number. There is one more way of defining an array −

var z = Array("Zara", "Nuha", "Ayan")

Following picture represents an array myList. Here, myList holds ten double values and the indices are from 0 to 9.

Scala Array

Processing Arrays

When processing array elements, we often use loop contol structures because all of the elements in an array are of the same type and the size of the array is known.

Below is an example program of showing how to create, initialize and process arrays −

Example

object Demo {
   def main(args: Array[String]) {
      var myList = Array(1.9, 2.9, 3.4, 3.5)
      
      // Print all the array elements
      for ( x <- myList ) {
         println( x )
      }
      // Summing all elements
      var total = 0.0;
      for ( i <- 0 to (myList.length - 1)) {
         total &plus;= myList(i);
      }
      println("Total is " + total);
      // Finding the largest element
      var max = myList(0);
      for ( i <- 1 to (myList.length - 1) ) {
         if (myList(i) > max) max = myList(i);
      }
      println("Max is " &plus; max);
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

Scala does not directly support various array operations and provides various methods to process arrays in any dimension. If you want to use the different methods then it is required to import Array._ package.

Scala Collections - Multi-Dimensional Array

There are many situations where you would need to define and use multi-dimensional arrays (i.e., arrays whose elements are arrays). For example, matrices and tables are examples of structures that can be realized as two-dimensional arrays.

The following is the example of defining a two-dimensional array −

var myMatrix = ofDim[Int](3,3)

This is an array that has three elements each being an array of integers that has three elements.

Try the following example program to process a multi-dimensional array −

Example

import Array._
object Demo {
   def main(args: Array[String]) {
      var myMatrix = ofDim[Int](3,3)
      // build a matrix
      for (i <- 0 to 2) {
         for ( j <- 0 to 2) {
            myMatrix(i)(j) = j;
         }
      }
      // Print two dimensional array
      for (i <- 0 to 2) {
         for ( j <- 0 to 2) {
            print(" " &plus; myMatrix(i)(j));
         }
         println();
      }
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

0 1 2
0 1 2
0 1 2

Scala Collections - Array with Range

Use of range() method to generate an array containing a sequence of increasing integers in a given range. You can use final argument as step to create the sequence; if you do not use final argument, then step would be assumed as 1.

Let us take an example of creating an array of range (10, 20, 2): It means creating an array with elements between 10 and 20 and range difference 2. Elements in the array are 10, 12, 14, 16, and 18.

Another example: range (10, 20). Here range difference is not given so by default it assumes 1 element. It create an array with the elements in between 10 and 20 with range difference 1. Elements in the array are 10, 11, 12, 13, ..., and 19.

The following example program shows how to create an array with ranges.

Example

import Array._
object Demo {
   def main(args: Array[String]) {
      var myList1 = range(10, 20, 2)
      var myList2 = range(10,20)
      // Print all the array elements
      for ( x <- myList1 ) {
         print( " " &plus; x )
      }
      println()
      for ( x <- myList2 ) {
         print( " " &plus; x )
      }
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

10 12 14 16 18
10 11 12 13 14 15 16 17 18 19

Scala Collections - ArrayBuffer

Scala provides a data structure, the ArrayBuffer, which can change size when initial size falls short. As array is of fix size and more elements cannot be occupied in an array, ArrayBuffer is an alternative to array where size is flexible.

Internally ArrayBuffer maintains an array of current size to store elements. When a new element is added, size is checked. In case underlying array is full then a new larger array is created and all elements are copied to larger array.

Declaring ArrayBuffer Variables

The following is the syntax for declaring an ArrayBuffer variable.

Syntax

var z = ArrayBuffer[String]()

Here, z is declared as an array-buffer of Strings which is initially empty. Values can be added by using commands like the following −

Command

z += "Zara";
z += "Nuha";
z += "Ayan";

Processing ArrayBuffer

Below is an example program of showing how to create, initialize and process ArrayBuffer −

Example

import scala.collection.mutable.ArrayBuffer 
object Demo {
   def main(args: Array[String]) = {
      var myList = ArrayBuffer("Zara","Nuha","Ayan")
      println(myList);
      // Add an element
      myList += "Welcome";
      // Add two element
      myList += ("To", "Howcodex");
      println(myList);
      // Remove an element
      myList -= "Welcome";
      // print second element
      println(myList(1));
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

ArrayBuffer(Zara, Nuha, Ayan)
ArrayBuffer(Zara, Nuha, Ayan, Welcome, To, Howcodex)
Nuha

Scala Collections - List

Scala Lists are quite similar to arrays which means, all the elements of a list have the same type but there are two important differences. First, lists are immutable, which means elements of a list cannot be changed by assignment. Second, lists represent a linked list whereas arrays are flat.

The type of a list that has elements of type T is written as List[T].

Try the following example, here are few lists defined for various data types.

// List of Strings
val fruit: List[String] = List("apples", "oranges", "pears")
// List of Integers
val nums: List[Int] = List(1, 2, 3, 4)
// Empty List.
val empty: List[Nothing] = List()
// Two dimensional list
val dim: List[List[Int]] = List(
   List(1, 0, 0),
   List(0, 1, 0),
   List(0, 0, 1)
)

All lists can be defined using two fundamental building blocks, a tail Nil and ::, which is pronounced cons. Nil also represents the empty list. All the above lists can be defined as follows.

// List of Strings
val fruit = "apples" :: ("oranges" :: ("pears" :: Nil))
// List of Integers
val nums = 1 :: (2 :: (3 :: (4 :: Nil)))
// Empty List.
val empty = Nil
// Two dimensional list
val dim = (1 :: (0 :: (0 :: Nil))) ::
   (0 :: (1 :: (0 :: Nil))) ::
   (0 :: (0 :: (1 :: Nil))) :: Nil

Basic Operations on Lists

All operations on lists can be expressed in terms of the following three methods.

Sr.No Methods & Description
1

head

This method returns the first element of a list.

2

tail

This method returns a list consisting of all elements except the first.

3

isEmpty

This method returns true if the list is empty otherwise false.

The following example shows how to use the above methods.

Example

object Demo {
   def main(args: Array[String]) {
      val fruit = "apples" :: ("oranges" :: ("pears" :: Nil))
      val nums = Nil
      println( "Head of fruit : " &plus; fruit.head )
      println( "Tail of fruit : " &plus; fruit.tail )
      println( "Check if fruit is empty : " &plus; fruit.isEmpty )
      println( "Check if nums is empty : " &plus; nums.isEmpty )
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Head of fruit : apples
Tail of fruit : List(oranges, pears)
Check if fruit is empty : false
Check if nums is empty : true

Concatenating Lists

You can use either ::: operator or List.:::() method or List.concat() method to add two or more lists. Please find the following example given below −

Example

object Demo {
   def main(args: Array[String]) {
      val fruit1 = "apples" :: ("oranges" :: ("pears" :: Nil))
      val fruit2 = "mangoes" :: ("banana" :: Nil)
      // use two or more lists with ::: operator
      var fruit = fruit1 ::: fruit2
      println( "fruit1 ::: fruit2 : " &plus; fruit )
      // use two lists with Set.:::() method
      fruit = fruit1.:::(fruit2)
      println( "fruit1.:::(fruit2) : " &plus; fruit )
      // pass two or more lists as arguments
      fruit = List.concat(fruit1, fruit2)
      println( "List.concat(fruit1, fruit2) : " &plus; fruit  )
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

fruit1 ::: fruit2 : List(apples, oranges, pears, mangoes, banana)
fruit1.:::(fruit2) : List(mangoes, banana, apples, oranges, pears)
List.concat(fruit1, fruit2) : List(apples, oranges, pears, mangoes, banana)

Creating Uniform Lists

You can use List.fill() method creates a list consisting of zero or more copies of the same element. Try the following example program.

Example

object Demo {
   def main(args: Array[String]) {
      val fruit = List.fill(3)("apples") // Repeats apples three times.
      println( "fruit : " &plus; fruit  )
      val num = List.fill(10)(2)         // Repeats 2, 10 times.
      println( "num : " &plus; num  )
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

fruit : List(apples, apples, apples)
num : List(2, 2, 2, 2, 2, 2, 2, 2, 2, 2)

Tabulating a Function

You can use a function along with List.tabulate() method to apply on all the elements of the list before tabulating the list. Its arguments are just like those of List.fill: the first argument list gives the dimensions of the list to create, and the second describes the elements of the list. The only difference is that instead of the elements being fixed, they are computed from a function.

Try the following example program.

Example

object Demo {
   def main(args: Array[String]) {
      // Creates 5 elements using the given function.
      val squares = List.tabulate(6)(n => n * n)
      println( "squares : " &plus; squares  )
      val mul = List.tabulate( 4,5 )( _ * _ )      
      println( "mul : " &plus; mul  )
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

squares : List(0, 1, 4, 9, 16, 25)
mul : List(List(0, 0, 0, 0, 0), List(0, 1, 2, 3, 4), 
   List(0, 2, 4, 6, 8), List(0, 3, 6, 9, 12))

Reverse List Order

You can use List.reverse method to reverse all elements of the list. The Following example shows the usage.

Example

object Demo {
   def main(args: Array[String]) {
      val fruit = "apples" :: ("oranges" :: ("pears" :: Nil))
      println( "Before reverse fruit : " &plus; fruit )
      println( "After reverse fruit : " &plus; fruit.reverse )
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Before reverse fruit : List(apples, oranges, pears)
After reverse fruit : List(pears, oranges, apples)

Scala Collections - ListBuffer

Scala provides a data structure, the ListBuffer, which is more efficient than List while adding/removing elements in a list. It provides methods to prepend, append elements to a list.

Declaring ListBuffer Variables

The following is the syntax for declaring an ListBuffer variable.

Syntax

var z = ListBuffer[String]()

Here, z is declared as an list-buffer of Strings which is initially empty. Values can be added by using commands like the following −

Command

z += "Zara";
z += "Nuha";
z += "Ayan";

Processing ListBuffer

Below is an example program of showing how to create, initialize and process ListBuffer −

Example

import scala.collection.mutable.ListBuffer 
object Demo {
   def main(args: Array[String]) = {
      var myList = ListBuffer("Zara","Nuha","Ayan")
      println(myList);
      // Add an element
      myList += "Welcome";
      // Add two element
      myList += ("To", "Howcodex");
      println(myList);
      // Remove an element
      myList -= "Welcome";
      // print second element
      println(myList(1));
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

ListBuffer(Zara, Nuha, Ayan)
ListBuffer(Zara, Nuha, Ayan, Welcome, To, Howcodex)
Nuha

Scala Collections - ListSet

Scala Set is a collection of pairwise different elements of the same type. In other words, a Set is a collection that contains no duplicate elements. ListSet implements immutable sets and uses list structure. Elements insertion order is preserved while storing the elements.

Declaring ListSet Variables

The following is the syntax for declaring an ListSet variable.

Syntax

var z : ListSet[String] = ListSet("Zara","Nuha","Ayan")

Here, z is declared as an list-set of Strings which has three members. Values can be added by using commands like the following −

Command

var myList1: ListSet[String] = myList + "Naira";

Processing ListSet

Below is an example program of showing how to create, initialize and process ListSet −

Example

import scala.collection.immutable.ListSet
object Demo {
   def main(args: Array[String]) = {
      var myList: ListSet[String] = ListSet("Zara","Nuha","Ayan");
      // Add an element
      var myList1: ListSet[String] = myList + "Naira";
      // Remove an element
      var myList2: ListSet[String] = myList - "Nuha";
      // Create empty set
      var myList3: ListSet[String] = ListSet.empty[String];
      println(myList);
      println(myList1);
      println(myList2);
      println(myList3);	  
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

ListSet(Zara, Nuha, Ayan)
ListSet(Zara, Nuha, Ayan, Naira)
ListSet(Zara, Ayan)
ListSet()

Scala Collections - Vector

Scala Vector is a general purpose immutable data structure where elements can be accessed randomly. It is generally used for large collections of data.

Declaring Vector Variables

The following is the syntax for declaring an Vector variable.

Syntax

var z : Vector[String] = Vector("Zara","Nuha","Ayan")

Here, z is declared as an vector of Strings which has three members. Values can be added by using commands like the following −

Command

var vector1: Vector[String] = z + "Naira";

Processing Vector

Below is an example program of showing how to create, initialize and process Vector −

Example

import scala.collection.immutable.Vector
object Demo {
   def main(args: Array[String]) = {
      var vector: Vector[String] = Vector("Zara","Nuha","Ayan");
      // Add an element
      var vector1: Vector[String] = vector :+ "Naira";
      // Reverse an element
      var vector2: Vector[String] = vector.reverse;
      // sort a vector
      var vector3: Vector[String] = vector1.sorted;
      println(vector);
      println(vector1);
      println(vector2);
      println(vector3);	  
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Vector(Zara, Nuha, Ayan)
Vector(Zara, Nuha, Ayan, Naira)
Vector(Ayan, Nuha, Zara)
Vector(Ayan, Naira, Nuha, Zara)

Scala Collections - Set

Scala Set is a collection of pairwise different elements of the same type. In other words, a Set is a collection that contains no duplicate elements. There are two kinds of Sets, the immutable and the mutable. The difference between mutable and immutable objects is that when an object is immutable, the object itself can't be changed.

By default, Scala uses the immutable Set. If you want to use the mutable Set, you'll have to import scala.collection.mutable.Set class explicitly. If you want to use both mutable and immutable sets in the same collection, then you can continue to refer to the immutable Set as Set but you can refer to the mutable Set as mutable.Set.

Here is how you can declare immutable Sets −

Syntax

// Empty set of integer type
var s : Set[Int] = Set()
// Set of integer type
var s : Set[Int] = Set(1,3,5,7)

or 

var s = Set(1,3,5,7)

While defining an empty set, the type annotation is necessary as the system needs to assign a concrete type to variable.

Basic Operations on set

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

Sr.No Methods & Description
1

head

This method returns the first element of a set.

2

tail

This method returns a set consisting of all elements except the first.

3

isEmpty

This method returns true if the set is empty otherwise false.

Try the following example showing usage of the basic operational methods −

Example

object Demo {
   def main(args: Array[String]) {
      val fruit = Set("apples", "oranges", "pears")
      val nums: Set[Int] = Set()
      println( "Head of fruit : " &plus; fruit.head )
      println( "Tail of fruit : " &plus; fruit.tail )
      println( "Check if fruit is empty : " &plus; fruit.isEmpty )
      println( "Check if nums is empty : " &plus; nums.isEmpty )
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Head of fruit : apples
Tail of fruit : Set(oranges, pears)
Check if fruit is empty : false
Check if nums is empty : true

Concatenating Sets

You can use either &plus;&plus; operator or Set.&plus;&plus;() method to concatenate two or more sets, but while adding sets it will remove duplicate elements.

The Following is the example to concatenate two sets.

Example

object Demo {
   def main(args: Array[String]) {
      val fruit1 = Set("apples", "oranges", "pears")
      val fruit2 = Set("mangoes", "banana")
      // use two or more sets with ++ as operator
      var fruit = fruit1 &plus;&plus; fruit2
      println( "fruit1 &plus;&plus; fruit2 : " &plus; fruit )
      // use two sets with ++ as method
      fruit = fruit1.&plus;&plus;(fruit2)
      println( "fruit1.&plus;&plus;(fruit2) : " &plus; fruit )
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

fruit1 &plus;&plus; fruit2 : Set(banana, apples, mangoes, pears, oranges)
fruit1.&plus;&plus;(fruit2) : Set(banana, apples, mangoes, pears, oranges)

Find Max, Min Elements in a Set

You can use Set.min method to find out the minimum and Set.max method to find out the maximum of the elements available in a set. Following is the example to show the program.

Example

object Demo {
   def main(args: Array[String]) {
      val num = Set(5,6,9,20,30,45)
      // find min and max of the elements
      println( "Min element in Set(5,6,9,20,30,45) : " &plus; num.min )
      println( "Max element in Set(5,6,9,20,30,45) : " &plus; num.max )
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Min element in Set(5,6,9,20,30,45) : 5
Max element in Set(5,6,9,20,30,45) : 45

Find Common Values Insets

You can use either Set.& method or Set.intersect method to find out the common values between two sets. Try the following example to show the usage.

Example

object Demo {
   def main(args: Array[String]) {
      val num1 = Set(5,6,9,20,30,45)
      val num2 = Set(50,60,9,20,35,55)
      // find common elements between two sets
      println( "num1.&(num2) : " &plus; num1.&(num2) )
      println( "num1.intersect(num2) : " &plus; num1.intersect(num2) )
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

num1.&(num2) : Set(20, 9)
num1.intersect(num2) : Set(20, 9)

Scala Collections - BitSet

Bitset is a common base class for mutable and immutable bitsets. Bitsets are sets of non-negative integers and are represented as variable-size arrays of bits packed into 64-bit words. The memory footprint of a bitset is represented by the largest number stored in it.

Declaring BitSet Variables

The following is the syntax for declaring an BitSet variable.

Syntax

var z : BitSet = BitSet(0,1,2)

Here, z is declared as an bit-set of non-negative integers which has three members. Values can be added by using commands like the following −

Command

var myList1: BitSet = myList + 3;

Processing BitSet

Below is an example program of showing how to create, initialize and process BitSet −

Example

import scala.collection.immutable.BitSet

object Demo {
   def main(args: Array[String]) = {
      var mySet: BitSet = BitSet(0, 1, 2);
      // Add an element
      var mySet1: BitSet = mySet + 3;
      // Remove an element
      var mySet2: BitSet = mySet - 2;
      var mySet3: BitSet = BitSet(4, 5);
      // Adding sets
      var mySet4: BitSet = mySet1 ++ mySet3;
      println(mySet);
      println(mySet1);
      println(mySet2);
      println(mySet4);	  
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

BitSet(0, 1, 2)
BitSet(0, 1, 2, 3)
BitSet(0, 1)
BitSet(0, 1, 2, 3, 4, 5)

Scala Collections - HashSet

Scala Set is a collection of pairwise different elements of the same type. In other words, a Set is a collection that contains no duplicate elements. HashSet implements immutable sets and uses hash table. Elements insertion order is not preserved.

Declaring HashSet Variables

The following is the syntax for declaring an HashSet variable.

Syntax

var z : HashSet[String] = HashSet("Zara","Nuha","Ayan")

Here, z is declared as an hash-set of Strings which has three members. Values can be added by using commands like the following −

Command

var myList1: HashSet[String] = myList + "Naira";

Processing HashSet

Below is an example program of showing how to create, initialize and process HashSet −

Example

import scala.collection.immutable.HashSet
object Demo {
   def main(args: Array[String]) = {
      var mySet: HashSet[String] = HashSet("Zara","Nuha","Ayan");
      // Add an element
      var mySet1: HashSet[String] = mySet + "Naira";
      // Remove an element
      var mySet2: HashSet[String] = mySet - "Nuha";
      // Create empty set
      var mySet3: HashSet[String] = HashSet.empty[String];
      println(mySet);
      println(mySet1);
      println(mySet2);
      println(mySet3);	  
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

HashSet(Zara, Nuha, Ayan)
HashSet(Zara, Nuha, Ayan, Naira)
HashSet(Zara, Ayan)
HashSet()

Scala Collections - TreeSet

Scala Set is a collection of pairwise different elements of the same type. In other words, a Set is a collection that contains no duplicate elements. TreeSet implements immutable sets and keeps elements in sorted order.

Declaring TreeSet Variables

The following is the syntax for declaring an TreeSet variable.

Syntax

var z : TreeSet[String] = TreeSet("Zara","Nuha","Ayan")

Here, z is declared as an tree-set of Strings which has three members. Values can be added by using commands like the following −

Command

var myList1: TreeSet[String] = myList + "Naira";

Processing TreeSet

Below is an example program of showing how to create, initialize and process TreeSet −

Example

import scala.collection.immutable.TreeSet

object Demo {
   def main(args: Array[String]) = {
      var mySet: TreeSet[String] = TreeSet("Zara","Nuha","Ayan");
      // Add an element
      var mySet1: TreeSet[String] = mySet + "Naira";
      // Remove an element
      var mySet2: TreeSet[String] = mySet - "Nuha";
      // Create empty set
      var mySet3: TreeSet[String] = TreeSet.empty[String];
      println(mySet);
      println(mySet1);
      println(mySet2);
      println(mySet3);	  
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

TreeSet(Ayan, Nuha, Zara)
TreeSet(Ayan, Naira, Nuha, Zara)
TreeSet(Ayan, Zara)
TreeSet()

Scala Collections - Map

Scala map is a collection of key/value pairs. Any value can be retrieved based on its key. Keys are unique in the Map, but values need not be unique. Maps are also called Hash tables. There are two kinds of Maps, the immutable and the mutable. The difference between mutable and immutable objects is that when an object is immutable, the object itself can't be changed.

By default, Scala uses the immutable Map. If you want to use the mutable Map, you'll have to import scala.collection.mutable.Map class explicitly. If you want to use both mutable and immutable Maps in the same, then you can continue to refer to the immutable Map as Map but you can refer to the mutable set as mutable.Map.

The Following is the example statements to declare immutable Maps −

// Empty hash table whose keys are strings and values are integers:
var A:Map[Char,Int] = Map()

// A map with keys and values.
val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF")

While defining empty map, the type annotation is necessary as the system needs to assign a concrete type to variable. If we want to add a key-value pair to a Map, we can use the operator + as follows.

A &plus; = ('I' -> 1)
A &plus; = ('J' -> 5)
A &plus; = ('K' -> 10)
A &plus; = ('L' -> 100)

Basic Operations on MAP

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

Sr.No Methods & Description
1

keys

This method returns an iterable containing each key in the map.

2

values

This method returns an iterable containing each value in the map.

3

isEmpty

This method returns true if the map is empty otherwise false.

Try the following example program showing usage of the Map methods.

Example

object Demo {
   def main(args: Array[String]) {
      val colors = Map(
         "red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F"
      )
      val nums: Map[Int, Int] = Map()
      println( "Keys in colors : " &plus; colors.keys )
      println( "Values in colors : " &plus; colors.values )
      println( "Check if colors is empty : " &plus; colors.isEmpty )
      println( "Check if nums is empty : " &plus; nums.isEmpty )
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Keys in colors : Set(red, azure, peru)
Values in colors : MapLike(#FF0000, #F0FFFF, #CD853F)
Check if colors is empty : false
Check if nums is empty : true

Concatenating Maps

You can use either &plus;&plus; operator or Map.&plus;&plus;() method to concatenate two or more Maps, but while adding Maps it will remove duplicate keys.

Try the following example program to concatenate two Maps.

Example

object Demo {
   def main(args: Array[String]) {
      val colors1 = Map(
         "red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F"
      )
      val colors2 = Map(
         "blue" -> "#0033FF", "yellow" -> "#FFFF00", "red" -> "#FF0000"
      )
      // use two or more Maps with &plus;&plus; as operator
      var colors = colors1 &plus;&plus; colors2
      println( "colors1 &plus;&plus; colors2 : " &plus; colors )
      // use two maps with &plus;&plus; as method
      colors = colors1.&plus;&plus;(colors2)
      println( "colors1.&plus;&plus;(colors2)) : " &plus; colors )
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

colors1 &plus;&plus; colors2 : Map(blue -> #0033FF, azure -> #F0FFFF, 
   peru -> #CD853F, yellow -> #FFFF00, red -> #FF0000)

colors1.&plus;&plus;(colors2)) : Map(blue -> #0033FF, azure -> #F0FFFF, 
   peru -> #CD853F, yellow -> #FFFF00, red -> #FF0000)

Print Keys and Values from a Map

You can iterate through the keys and values of a Map using "foreach" loop. Here, we used method foreach associated with iterator to walk through the keys. Following is the example program.

Example

object Demo {
   def main(args: Array[String]) {
      val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF","peru" -> "#CD853F")

      colors.keys.foreach{
         i =>  
         print( "Key = " &plus; i )
         println(" Value = " &plus; colors(i) )
      }
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Key = red Value = #FF0000
Key = azure Value = #F0FFFF
Key = peru Value = #CD853F

Check for a key in Map

You can use either Map.contains method to test if a given key exists in the map or not. Try the Following example program to key checking.

Example

object Demo {
   def main(args: Array[String]) {
      val colors = Map(
         "red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F"
      )
      if( colors.contains( "red" )) {
         println("Red key exists with value :"  &plus; colors("red"))
      } else {
         println("Red key does not exist")
      }
      if( colors.contains( "maroon" )) {
         println("Maroon key exists with value :"  &plus; colors("maroon"))
      } else {
         println("Maroon key does not exist")
      }
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Red key exists with value :#FF0000
Maroon key does not exist

Scala Collections - HashMap

Scala map is a collection of key/value pairs. Any value can be retrieved based on its key. Keys are unique in the Map, but values need not be unique. HashMap implements immutable map and uses hash table to implement the same.

Declaring HashMap Variables

The following is the syntax for declaring an HashMap variable.

Syntax

val colors = HashMap("red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F")

Here, colors is declared as an hash-map of Strings, Int which has three key-value pairs. Values can be added by using commands like the following −

Command

var myMap1: HashMap[Char, Int] = colors + ("black" -> "#000000");

Processing HashMap

Below is an example program of showing how to create, initialize and process HashMap −

Example

import scala.collection.immutable.HashMap
object Demo {
   def main(args: Array[String]) = {
      var myMap: HashMap[String,String] = HashMap(
         "red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F"
      );
      // Add an element
      var myMap1: HashMap[String,String] = myMap + ("white" -> "#FFFFFF");
      // Print key values
      myMap.keys.foreach{ 
         i =>  
         print( "Key = " + i )
         println(" Value = " + myMap(i) )
      }
      if( myMap.contains( "red" )) {
         println("Red key exists with value :"  + myMap("red"))
      } else {
         println("Red key does not exist")
      }
      if( myMap.contains( "maroon" )) {
         println("Maroon key exists with value :"  + myMap("maroon"))
      } else {
         println("Maroon key does not exist")
      }
      //removing element
      var myMap2: HashMap[String,String] = myMap - ("white");
      // Create empty map
      var myMap3: HashMap[String,String] = HashMap.empty[String, String];
      println(myMap1);
      println(myMap2);
      println(myMap3);		  
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Key = azure Value = #F0FFFF
Key = peru Value = #CD853F
Key = red Value = #FF0000
Red key exists with value :#FF0000
Maroon key does not exist
HashMap(azure -> #F0FFFF, peru -> #CD853F, white -> #FFFFFF, red -> #FF0000)
HashMap(azure -> #F0FFFF, peru -> #CD853F, red -> #FF0000)
HashMap()

Scala Collections - ListMap

Scala map is a collection of key/value pairs. Any value can be retrieved based on its key. Keys are unique in the Map, but values need not be unique. ListMap implements immutable map and uses list to implement the same. It is used with small number of elements.

Declaring ListMap Variables

The following is the syntax for declaring an ListMap variable.

Syntax

val colors = ListMap("red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F")

Here, colors is declared as an hash-map of Strings, Int which has three key-value pairs. Values can be added by using commands like the following −

Command

var myMap1: ListMap[Char, Int] = colors + ("black" -> "#000000");

Processing ListMap

Below is an example program of showing how to create, initialize and process ListMap −

Example

import scala.collection.immutable.ListMap

object Demo {
   def main(args: Array[String]) = {
      var myMap: ListMap[String,String] = ListMap(
         "red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F"
      );
      // Add an element
      var myMap1: ListMap[String,String] = myMap + ("white" -> "#FFFFFF");
      // Print key values
      myMap.keys.foreach{ 
         i =>  
         print( "Key = " + i )
         println(" Value = " + myMap(i) ) 
      }
      if( myMap.contains( "red" )) {
         println("Red key exists with value :"  + myMap("red"))
      } else {
         println("Red key does not exist")
      }
      if( myMap.contains( "maroon" )) {
         println("Maroon key exists with value :"  + myMap("maroon"))
      } else {
         println("Maroon key does not exist")
      }
      //removing element
      var myMap2: ListMap[String,String] = myMap - ("white");
      // Create empty map
      var myMap3: ListMap[String,String] = ListMap.empty[String, String];
      println(myMap1);
      println(myMap2);	
      println(myMap3);		  
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Key = red Value = #FF0000
Key = azure Value = #F0FFFF
Key = peru Value = #CD853F
Red key exists with value :#FF0000
Maroon key does not exist
ListMap(red -> #FF0000, azure -> #F0FFFF, peru -> #CD853F, white -> #FFFFFF)
ListMap(red -> #FF0000, azure -> #F0FFFF, peru -> #CD853F)
ListMap()

Scala Collections - Iterator

An iterator is not a collection, but rather a way to access the elements of a collection one by one. The two basic operations on an iterator it are next and hasNext. A call to it.next() will return the next element of the iterator and advance the state of the iterator. You can find out whether there are more elements to return using Iterator's it.hasNext method.

The most straightforward way to "step through" all the elements returned by an iterator is to use a while loop. Let us follow the following example program.

Example

object Demo {
   def main(args: Array[String]) {
      val it = Iterator("a", "number", "of", "words")
      while (it.hasNext){
         println(it.next())
      }
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

a
number
of
words

Find Min & Max Valued Element

You can use it.min and it.max methods to find out the minimum and maximum valued elements from an iterator. Here, we used ita and itb to perform two different operations because iterator can be traversed only once. Following is the example program.

Example

object Demo {
   def main(args: Array[String]) {
      val ita = Iterator(20,40,2,50,69, 90)
      val itb = Iterator(20,40,2,50,69, 90)
      println("Maximum valued element " &plus; ita.max )
      println("Minimum valued element " &plus; itb.min )
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Maximum valued element 90
Minimum valued element 2

Find the Length of the Iterator

You can use either it.size or it.length methods to find out the number of elements available in an iterator. Here, we used ita and itb to perform two different operations because iterator can be traversed only once. Following is the example program.

Example

object Demo {
   def main(args: Array[String]) {
      val ita = Iterator(20,40,2,50,69, 90)
      val itb = Iterator(20,40,2,50,69, 90)
      println("Value of ita.size : " &plus; ita.size )
      println("Value of itb.length : " &plus; itb.length )
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Value of ita.size : 6
Value of itb.length : 6

Scala Collections - Option

Scala Option[ T ] is a container for zero or one element of a given type. An Option[T] can be either Some[T] or None object, which represents a missing value. For instance, the get method of Scala's Map produces Some(value) if a value corresponding to a given key has been found, or None if the given key is not defined in the Map.

Option type is used frequently in Scala programs and you can compare this with the null value available in Java which indicate no value. For example, the get method of java.util.HashMap returns either a value stored in the HashMap, or null if no value was found.

Let's say we have a method that retrieves a record from the database based on a primary key.

def findPerson(key: Int): Option[Person]

The method will return Some[Person] if the record is found but None if the record is not found. Let us follow the following program.

Example

object Demo {
   def main(args: Array[String]) {
      val capitals = Map("France" -> "Paris", "Japan" -> "Tokyo")
      println("capitals.get( \"France\" ) : " &plus;  capitals.get( "France" ))
      println("capitals.get( \"India\" ) : " &plus;  capitals.get( "India" ))
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

capitals.get( "France" ) : Some(Paris)
capitals.get( "India" ) : None

The most common way to take optional values apart is through a pattern match. For example try the following program.

Example

object Demo {
   def main(args: Array[String]) {
      val capitals = Map("France" -> "Paris", "Japan" -> "Tokyo")
      println("show(capitals.get( \"Japan\")) : " &plus; show(capitals.get( "Japan")) )
      println("show(capitals.get( \"India\")) : " &plus; show(capitals.get( "India")) )
   }
   def show(x: Option[String]) = x match {
      case Some(s) => s
      case None => "?"
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

show(capitals.get( "Japan")) : Tokyo
show(capitals.get( "India")) : ?

Using getOrElse() Method

Following is the example program to show how to use getOrElse() method to access a value or a default when no value is present.

Example

object Demo {
   def main(args: Array[String]) {
      val a:Option[Int] = Some(5)
      val b:Option[Int] = None 
      println("a.getOrElse(0): " &plus; a.getOrElse(0) )
      println("b.getOrElse(10): " &plus; b.getOrElse(10) )
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

a.getOrElse(0): 5
b.getOrElse(10): 10

Using isEmpty() Method

Following is the example program to show how to use isEmpty() method to check if the option is None or not.

Example

object Demo {
   def main(args: Array[String]) {
      val a:Option[Int] = Some(5)
      val b:Option[Int] = None 
      println("a.isEmpty: " + a.isEmpty )
      println("b.isEmpty: " + b.isEmpty )
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Example

a.isEmpty: false
b.isEmpty: true

Scala Collections - Queue

Queue is First In First Out, FIFO data structure and allows to insert and retrieve elements in FIFO manner.

Declaring Queue Variables

The following is the syntax for declaring an Queue variable.

Syntax

val queue = Queue(1, 2, 3, 4, 5)

Here, queue is declared as an Queue of numbers. Value can be added at front by using commands like the following −

Command

queue.enqueue(6)

Value can be retrived at front by using commands like the following −

Command

queue.dequeue()

Processing Queue

Below is an example program of showing how to create, initialize and process Queue −

Example

import scala.collection.mutable.Queue
object Demo {
   def main(args: Array[String]) = {
      var queue = Queue(1, 2, 3, 4, 5);
      // Print queue elements
      queue.foreach{(element:Int) => print(element + " ")}
      println();
      // Print first element
      println("First Element: " + queue.front)
      // Add an element
      queue.enqueue(6);
      // Print queue elements
      queue.foreach{(element:Int) => print(element+ " ")}
      println();
      // Remove an element
      var dq = queue.dequeue;
      // Print dequeued element
      println("Dequeued Element: " + dq)
      // Print queue elements
      queue.foreach{(element:Int) => print(element+ " ")}
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

1 2 3 4 5
First Element: 1
1 2 3 4 5 6
Dequeued Element: 1
2 3 4 5 6

Scala Collections - Tuple

Scala tuple combines a fixed number of items together so that they can be passed around as a whole. Unlike an array or list, a tuple can hold objects with different types but they are also immutable.

The following is an example of a tuple holding an integer, a string, and the console.

val t = (1, "hello", Console)

Which is syntactic sugar (short cut) for the following −

val t = new Tuple3(1, "hello", Console)

The actual type of a tuple depends upon the number and of elements it contains and the types of those elements. Thus, the type of (99, "Luftballons") is Tuple2[Int, String]. The type of ('u', 'r', "the", 1, 4, "me") is Tuple6[Char, Char, String, Int, Int, String]

Tuples are of type Tuple1, Tuple2, Tuple3 and so on. There currently is an upper limit of 22 in the Scala if you need more, then you can use a collection, not a tuple. For each TupleN type, where 1 <= N <= 22, Scala defines a number of element-access methods. Given the following definition −

val t = (4,3,2,1)

To access elements of a tuple t, you can use method t._1 to access the first element, t._2 to access the second, and so on. For example, the following expression computes the sum of all elements of t.

val sum = t._1 &plus; t._2 &plus; t._3 &plus; t._4

You can use Tuple to write a method that takes a List[Double] and returns the count, the sum, and the sum of squares returned in a three-element Tuple, a Tuple3[Int, Double, Double]. They are also useful to pass a list of data values as messages between actors in concurrent programming.

Try the following example program. It shows how to use a tuple.

Example

object Demo {
   def main(args: Array[String]) {
      val t = (4,3,2,1)
      val sum = t._1 &plus; t._2 &plus; t._3 &plus; t._4
      println( "Sum of elements: "  &plus; sum )
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Commands

\>scalac Demo.scala
\>scala Demo

Output

Sum of elements: 10

Iterate over the Tuple

You can use Tuple.productIterator() method to iterate over all the elements of a Tuple.

Try the following example program to iterate over tuples.

Example

object Demo {
   def main(args: Array[String]) {
      val t = (4,3,2,1)
      t.productIterator.foreach{ i =>println("Value = " &plus; i )}
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Commands

\>scalac Demo.scala
\>scala Demo

Output

Value = 4
Value = 3
Value = 2
Value = 1

Converting to String

You can use Tuple.toString() method to concatenate all the elements of the tuple into a string. Try the following example program to convert to String.

Example

object Demo {
   def main(args: Array[String]) {
      val t = new Tuple3(1, "hello", Console)
      println("Concatenated String: " &plus; t.toString() )
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Concatenated String: (1,hello,scala.Console$@281acd47)

Swap the Elements

You can use Tuple.swap method to swap the elements of a Tuple2.

Try the following example program to swap the elements.

Example

object Demo {
   def main(args: Array[String]) {
      val t = new Tuple2("Scala", "hello")
      println("Swapped Tuple: " &plus; t.swap )
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Swapped tuple: (hello,Scala)

Scala Collections - Seq

Scala Seq is a trait to represent immutable sequences. This structure provides index based access and various utility methods to find elements, their occurences and subsequences. A Seq maintains the insertion order.

Declaring Seq Variables

The following is the syntax for declaring an Seq variable.

Syntax

val seq: Seq[Int] = Seq(1, 2, 3, 4, 5)

Here, seq is declared as an Seq of numbers. Seq provides commands like the following −

Command

val isPresent = seq.contains(4);
val contains = seq.endsWith(Seq(4,5));
var lastIndexOf = seq.lasIndexOf(5);

Processing Seq

Below is an example program of showing how to create, initialize and process Seq −

Example

import scala.collection.immutable.Seq
object Demo {
   def main(args: Array[String]) = {
      var seq = Seq(1, 2, 3, 4, 5, 3)
      // Print seq elements
      seq.foreach{(element:Int) => print(element + " ")}
      println()
      println("Seq ends with (5,3): " + seq.endsWith(Seq(5, 3)))
      println("Seq contains 4: " + seq.contains(4))
      println("Last index of 3: " + seq.lastIndexOf(3))
      println("Reversed Seq" + seq.reverse)           
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

1 2 3 4 5 3
Seq ends with (5,3): true
Seq contains 4: true
Last index of 3: 5
Reversed SeqList(3, 5, 4, 3, 2, 1)

Scala Collections - Stack

Stack is Last In First Out, LIFO data structure and allows to insert and retrieve element at top, in LIFO manner.

Declaring Stack Variables

The following is the syntax for declaring an Stack variable.

Syntax

val stack = Stack(1, 2, 3, 4, 5)

Here, stack is declared as an Stack of numbers. Value can be added at top by using commands like the following −

Command

stack.push(6)

Value can be retrived from top by using commands like the following −

Command

stack.top

Value can be removed from top by using commands like the following −

Command

stack.pop

Processing Stack

Below is an example program of showing how to create, initialize and process Stack −

Example

import scala.collection.mutable.Stack
object Demo {
   def main(args: Array[String]) = {
      var stack: Stack[Int] = Stack();
      // Add elements
      stack.push(1);
      stack.push(2);
      // Print element at top
      println("Top Element: " + stack.top)
      // Print element
      println("Removed Element: " + stack.pop())
      // Print element
      println("Top Element: " + stack.top)	
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Top Element: 2
Removed Element: 2
Top Element: 1

Scala Collections - Stream

Scala Stream is special list with lazy evaluation feature. In scala stream, elements are evaluated only when they are needed. Stream supports lazy computation and is performance savvy.

Declaring Stream Variables

The following is the syntax for declaring an Stream variable.

Syntax

val stream = 1 #:: 2 #:: 3 #:: Stream.empty

Here, stream is declared as a stream of numbers. Here 1 is head of stream, 2, 3 are tail of stream. Stream.empty marks the end of the stream. Values can be retrived using take commands like the following −

Command

stream.take(2)

Processing Stream

Below is an example program of showing how to create, initialize and process Stream −

Example

import scala.collection.immutable.Stream
object Demo {
   def main(args: Array[String]) = {
      val stream = 1 #:: 2 #:: 3 #:: Stream.empty
      // print stream
      println(stream)
      // Print first two elements	
      stream.take(2).print
      println()
      // Create an empty stream
      val stream1: Stream[Int] = Stream.empty[Int]
      // Print element
      println(s"Stream: $stream1")
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Stream(1, <not computed>)
1, 2
Stream: Stream()

Scala Collections - Drop Method

drop() method is method used by List to select all elements except first n elements of the list.

Syntax

The following is the syntax of drop method.

def drop(n: Int): List[A]

Here, n is the number of elements to be dropped from the list. This method returns the all the elements of list except first n ones.

Usage

Below is an example program of showing how to use drop method −

Example

object Demo {
   def main(args: Array[String]) = {
      val list = List(1, 2, 3, 4, 5)
      // print list
      println(list)
      //apply operation
      val result = list.drop(3)
      //print result
      println(result)      
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

List(1, 2, 3, 4, 5)
List(4, 5)

Scala Collections - DropWhile Method

dropWhile() method is method used by List to drop all elements which satisfies a given condition.

Syntax

The following is the syntax of dropWhile method.

def dropWhile(p: (A) => Boolean): List[A]

Here, p: (A) => Boolean is a predicate or condition to be applied on each element of the list. This method returns the all the elements of list except dropped ones.

Usage

Below is an example program of showing how to use dropWhile method −

Example

object Demo {
   def main(args: Array[String]) = {
      val list = List(3, 6, 9, 4, 2)
      // print list
      println(list)
      //apply operation
      val result = list.dropWhile(x=>{x % 3 == 0})
      //print result
      println(result)      
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

List(3, 6, 9, 4, 2)
List(4, 2)

Scala Collections - Filter Method

filter() method is method used by List to select all elements which satisfies a given predicate.

Syntax

The following is the syntax of filter method.

def filter(p: (A) => Boolean): List[A]

Here, p: (A) => Boolean is a predicate or condition to be applied on each element of the list. This method returns the all the elements of list which satisfiles the given condition.

Usage

Below is an example program of showing how to use filter method −

Example

object Demo {
   def main(args: Array[String]) = {
      val list = List(3, 6, 9, 4, 2)
      // print list
      println(list)
      //apply operation
      val result = list.filter(x=>{x % 3 == 0})
      //print result
      println(result)      
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

List(3, 6, 9, 4, 2)
List(3, 6, 9)

Scala Collections - Find Method

find() method is method used by Iterators to find an element which satisfies a given predicate.

Syntax

The following is the syntax of find method.

def find(p: (A) => Boolean): Option[A]

Here, p: (A) => Boolean is a predicate or condition to be applied on each element of the iterator. This method returns the Option element containing the matched element of iterator which satisfiles the given condition.

Usage

Below is an example program of showing how to use find method −

Example

object Demo {
   def main(args: Array[String]) = {
      val iterator = Iterator(3, 6, 9, 4, 2)
      //apply operation
      val result = iterator.find(x=>{x % 3 == 0})
      //print result
      println(result)      
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Some(3)

Scala Collections - FlatMap Method

flatMap() method is method of TraversableLike trait, it takes a predicate, applies it to each element of the collection and returns a new collection of elements returned by the predicate.

Syntax

The following is the syntax of flatMap method.

def flatMap[B](f: (A) ? GenTraversableOnce[B]): TraversableOnce[B]

Here, f: (A) ? GenTraversableOnce[B] is a predicate or condition to be applied on each element of the collection. This method returns the Option element containing the matched element of iterator which satisfiles the given condition.

Usage

Below is an example program of showing how to use flatMap method −

Example

object Demo {
   def main(args: Array[String]) = {
      val list = List(1, 5, 10)
      //apply operation
      val result = list.flatMap{x => List(x,x+1)}
      //print result
      println(result)      
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

List(1, 2, 5, 6, 10, 11)

Scala Collections - Flatten Method

flatten() method is a member GenericTraversableTemplate trait, it returns a single collection of elements by merging child collections.

Syntax

The following is the syntax of flatten method.

def flatten[B]: Traversable[B]

Here, f: (A) ? GenTraversableOnce[B] is a predicate or condition to be applied on each element of the collection. This method returns the Option element containing the matched element of iterator which satisfiles the given condition.

Usage

Below is an example program of showing how to use flatten method −

Example

object Demo {
   def main(args: Array[String]) = {
      val list = List(List(1,2), List(3,4))
      //apply operation
      val result = list.flatten
      //print result
      println(result)      
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

List(1, 2, 3, 4)

Scala Collections - Fold Method

fold() method is a member of TraversableOnce trait, it is used to collapse elements of collections.

Syntax

The following is the syntax of fold method.

def fold[A1 >: A](z: A1)(op: (A1, A1) ? A1): A1

Here, fold method takes associative binary operator function as a parameter. This method returns the result as value. It considers first input as initial value and second input as a function (which takes accumulated value and current item as input).

Usage

Below is an example program of showing how to use fold method −

Example

object Demo {
   def main(args: Array[String]) = {
      val list = List(1, 2, 3 ,4)
      //apply operation to get sum of all elements of the list
      val result = list.fold(0)(_ + _)
      //print result
      println(result)      
   }
}

Here we've passed 0 as initial value to fold function and then all values are added. Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

10

Scala Collections - FoldLeft Method

foldLeft() method is a member of TraversableOnce trait, it is used to collapse elements of collections. It navigates elements from Left to Right order. It is primarily used in recursive functions and prevents stack overflow exceptions.

Syntax

The following is the syntax of fold method.

def foldLeft[B](z: B)(op: (B, A) ? B): B

Here, foldLeft method takes associative binary operator function as a parameter. This method returns the result as value.

Usage

Below is an example program of showing how to use foldLeft method −

Example

object Demo {
   def main(args: Array[String]) = {
      val list = List(1, 2, 3 ,4)
      //apply operation to get sum of all elements of the list
      val result = list.foldLeft(0)(_ + _)
      //print result
      println(result)      
   }
}

Here we've passed 0 as initial value to fold function and then all values are added. Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

10

Scala Collections - FoldRight Method

foldRight() method is a member of TraversableOnce trait, it is used to collapse elements of collections. It navigates elements from Right to Left order.

Syntax

The following is the syntax of foldRight method.

def foldRight[B](z: B)(op: (B, A) ? B): B

Here, fold method takes associative binary operator function as a parameter. This method returns the resulted value.

Usage

Below is an example program of showing how to use foldRight method −

Example

object Demo {
   def main(args: Array[String]) = {
      val list = List(1, 2, 3 ,4)
      //apply operation to get sum of all elements of the list
      val result = list.foldRight(0)(_ + _)
      //print result
      println(result)      
   }
}

Here we've passed 0 as initial value to foldRight function and then all values are added. Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

10

Scala Collections - Map Method

map() method is a member of TraversableLike trait, it is used to run a predicate method on each elements of a collection. It returns a new collection.

Syntax

The following is the syntax of map method.

def map[B](f: (A) ? B): Traversable[B]

Here, map method takes a prediate function as a parameter. This method returns the updated collection.

Usage

Below is an example program of showing how to use map method −

Example

object Demo {
   def main(args: Array[String]) = {
      val list = List(1, 2, 3 ,4)
      //apply operation to get twice of each element.
      val result = list.map(_ * 2)
      //print result
      println(result)      
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

List(2, 4, 6, 8)

Scala Collections - Partition Method

partition() method is a member of TraversableLike trait, it is used to run a predicate method on each elements of a collection. It returns two collections, one collection is of elements which satisfiles a given predicate function and another collection is of elements which do not satisfy the given predicate function.

Syntax

The following is the syntax of map method.

def partition(p: (A) ? Boolean): (Repr, Repr)

Here, partition method takes a prediate function as a parameter. This method returns the collections.

Usage

Below is an example program of showing how to use partition method −

Example

object Demo {
   def main(args: Array[String]) = {
      val list = List(1, 2, 3, 4, 5, 6, 7)
      //apply operation to get twice of each element.
      val (result1, result2) = list.partition(x=>{x % 3 == 0})
      //print result
      println(result1)
      println(result2)      
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

List(3, 6)
List(1, 2, 4, 5, 7)

Scala Collections - Reduce Method

reduce() method is a member of TraversableOnce trait, it is used to collapse elements of collections. It is similar to fold method but it does not take initial value.

Syntax

The following is the syntax of reduce method.

def reduce[A1 >: A](op: (A1, A1) ? A1): A1

Here, reduce method takes associative binary operator function as a parameter. This method returns the resultant value.

Usage

Below is an example program of showing how to use fold method −

Example

object Demo {
   def main(args: Array[String]) = {
      val list = List(1, 2, 3 ,4)
      //apply operation to get sum of all elements of the list
      val result = list.reduce(_ + _)
      //print result
      println(result)      
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

10

Scala Collections - Scan Method

scan() method is a member of TraversableLike trait, it is similar to fold method but is used to apply a operation on each elements of collection and return a collection.

Syntax

The following is the syntax of fold method.

def scan[B >: A, That](z: B)(op: (B, B) ? B)(implicit cbf: CanBuildFrom[Repr, B, That]): That

Here, scan method takes associative binary operator function as a parameter. This method returns the updated collection as result. It considers first input as initial value and second input as a function.

Usage

Below is an example program of showing how to use scan method −

Example

object Demo {
   def main(args: Array[String]) = {
      val list = List(1, 2, 3 ,4)
      //apply operation to create a running total of all elements of the list
      val list1 = list.scan(0)(_ + _)
      //print list
      println(list1)      
   }
}

Here we've passed 0 as initial value to scan function and then all values are added. Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

List(0, 1, 3, 6, 10)

Scala Collections - Zip Method

zip() method is a member of IterableLike trait, it is used to merge a collection to current collection and result is a collection of pair of tuple elements from both collections.

Syntax

The following is the syntax of zip method.

def zip[B](that: GenIterable[B]): Iterable[(A, B)]

Here, zip method takes a collection as parameter. This method returns the updated collection of pair as result.

Usage

Below is an example program of showing how to use zip method −

Example

object Demo {
   def main(args: Array[String]) = {
      val list = List(1, 2, 3 ,4)
      val list1 = List("A", "B", "C", "D")
      //apply operation to create a zip of list
      val list2 = list zip list1
      //print list
      println(list2)      
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

List((1,A), (2,B), (3,C), (4,D))
Advertisements