It’s all about the Sets and Maps in Scala

Reading Time: 5 minutes

INTRODUCTION

Data Structure can be defined as the group of data elements that provides an efficient way of storing and organizing data in the computer so that it can be used efficiently. Some examples of Data Structures are arrays, Linked List, Stack, Queue, etc. The sets and maps are the most common topic in collections where can use so many places.scala’s collection framework provides two important interfaces: Sets and Maps. It is possible to store a collection of objects as a single unit using Set and Map interfaces. The main difference between Sets and Maps is that Set contains different elements, whereas Map contains the data in key-value pairs.

Introduction to Scala Collections

Basically, collections are containers of things. The collection classes can be found in the package scala. collection. Collections are of two types –

  • Mutable Collections
  • Immutable Collections

Mutable Collection –All classes in scala. collection. mutable package belongs to the Mutable collection type. . Mutable Collection be able to be changed following created
Immutable Collection – In Immutable Collection, It does not agree to change data. Scala imports this package by default. If you desire the mutable collection, you have to import scala.collection.mutable package in your code.

SET

A set is a collection of items that are unique. Each set is unique because of the == method it holds. If you add a duplicate item, set silently discards the request.

Syntax:

 Mutable Set
var variable_name: Set[type] = Set(item1, item2, item3)
or
var variable_name = Set(item1, item2, item3)

 Immutable set
val variable_name: Set[type] = Set(item1, item2, item3)
or
val variable_name = Set(item1, item2, item3)

Basic operations Of Sets:

HEAD: This method returns the first element of a set. If the set is empty, the method returns true, otherwise false.

TAIL: This method returns a set that contains all elements except the first.

IsEmpty: When this method returns true, the set is empty, else it returns false.

Setting up Scala in a way that works:

  • There are two kinds of sets in Scala: mutable and immutable. A mutable set changes the value of the object, while an immutable set does not change the object’s value.
  • As far as Scala is concerned, an immutable set is found under the Scala.collection.immutable._ package, while a mutable set is under the Scala.collection.mutable._ package.
  • The Scala.collection.immutable._ package can be used to define mutable sets as well.
  • It is possible to create an empty set in Scala.
  • In Scala, immutable objects are the default.

EXAMPLE:

// use of immutable set
import scala.collection.immutable._

object Main
{
  def main(args: Array[String])
  {

    // Creating and initializing immutable sets
    val names: Set[String] = Set("Emily", "Smith",
      "Johnsons", "Adler")
    val age = Set("22", "23", "25", "21")

    // Display the value of names
    println("Name:"+names)
    println("\nAge:"+age)
  }

}
This image has an empty alt attribute; its file name is 1exam.png

EXAMPLE:

import scala.collection.mutable._

object Fruits {
    def main(args: Array[String])
    {
     // Creating and initializing mutable sets
      val fruitsSet: Set[String] = Set("Apple", "Grapes", "Orange", "Peach")
      val numbersSet = Set(1,2,3,4)

      //Display the value of myset1
      println("Set 1:"+fruitsSet)
    //  Display the value of myset2
      println("\nSet 2:"+numbersSet)
    }


This image has an empty alt attribute; its file name is 555.png

Sorted Set

Sets store non-repeatable elements, and sort them in a set so that elements appear in a certain order. SortedSets guarantee the order of elements.

a sorted set is a trait that provides the Set semantics but also allows you to drive the ordering of the elements within the SortedSet.

Initiating a SortedSet with 3 elements:

import scala.collection.mutable.SortedSet
val Data: SortedSet[String] = SortedSet("Rex","cody","zack")
println(s"Elements of Data = $Data")

How to add elements to SortedSet:

import scala.collection.mutable.SortedSet
Data += "Roy"
println(s"Elements = $Data")

Map

There are two kinds of Maps: the immutable and the mutable. All values can be established by searching under a key in the Map. in general, Scala utilizes immutable Map class; we require to import the scala.collection.mutable.Map class to use mutable Map.

Syntax :

Mutable
variable = scala.collection.mutable.Map(key_1 -> value_1, 
key_2 -> value_2, key_3 -> value_3)

Immutable
variable = Map(key_1 -> value_1, key_2 -> value_2,
 key_3 -> value_3)

Operations on a Scala Map

Using Scala Map, we can perform the following three basic operations:

  • Keys – A scale map’s keys are returned as an iterablein this method.
  • values -Scala map values can be obtained by using the Value method.
  • Is Empty – Maps can be empty using the Scala isEmpty method that returns true if they are empty. Otherwise, they return false.

EXAMPLE:

object Main{
  def main(args:Array[String])
  {
    val names = Map( 1->"Bob",  2->"Angelina" , 3->"Gwen" )
    val matcher = names(1)
    println(matcher)
  }
}
This image has an empty alt attribute; its file name is 66.png

Updating the values

In the case of immutable maps, Scala will output an error when you try to update values. However, mutable maps accept any changes that are made to key values.

Example:

object Main
{

  def main(args:Array[String])
  {

    val Names = scala.collection.mutable.Map("Emily" -> 10,
      "John" -> 20,
      "Alisha" -> 30)
    println("Before Updating: " + Names)

    // Updating
    Names("Emily") = 40

    println("After Updating: " + Names)
  }
}
This image has an empty alt attribute; its file name is exam2.png

Adding new key-value pair

An added or updated pair of keys can be inserted using the += operator in a mutable map.

Example:

object Main
{

  def main(args:Array[String])
  {

    val Names = scala.collection.mutable.Map("Sam" -> 10,
      "Tom" -> 20,
      "Ali" -> 30)

    println("Before Adding: "+Names)

    //Adding a new key "Phils"
    //updating an existing key "Sam"

    Names += ("Phils" -> 100, "Sam" -> 40)

    println("After Adding: "+Names)
  }
}
This image has an empty alt attribute; its file name is exam.png

Iteration in a Map

When performing an iteration loop, a variable should be a pair for key-value pairs.

EXAMPLE:

object Main
{
  def main(args:Array[String])
  {

    val Names = scala.collection.mutable.Map("Harry" -> 10,
      "Tom" -> 20,
      "Elice" -> 30)

    // (k, v) is a tuple with two elements
    for((k, v) <- Names)
    {
      //where k is key and v is value
      print("Key:"+k+", ")
      println("Value:"+v)
    }
  }
}

This image has an empty alt attribute; its file name is exam4.png

Empty Map

It is also possible to create a Scala Map that is empty and fill it with elements later.

EXAMPLE:

object Main
{
  def main(args:Array[String])
  {
    val Data = scala.collection.mutable.Map[String, Int]()

    println("Empty: " + Data)

    // Adding new entry
    Data += ("Charlie" -> 50)

    println("New Entry: " + Data)
  }
}

Links:

https://docs.scala-lang.org/
https://www.tutorialspoint.com/scala/index.htm

Written by 

Rahul is a Software Developer Trainee. He has completed his graduation from Ambedkar Institute of Technology. He likes to travel and Explore new Things. He is also a kabaddi player. He writes about Technology and Coding in his spare time.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading