Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala
maps

What are maps in Scala?

Sarvech Qadir

Scala maps are like dictionaries; a combination of key-value pairs. By definition, key-value pairs are uniquely identified in the map. Any key can be directly used to access a value. It is important for keys to be unique, but values do not need to be unique.

In Scala, there are two kinds of maps: Mutable and Immutable. A mutable map object’s value can be changed, while immutable maps do not allow the values associated with keys to be changed.

Scala uses immutable maps by default. You can import scala.collection.mutable.Map to use mutable maps.

Visual representation of maps in Scala
Visual representation of maps in Scala

Syntax

The following is the syntax to declare a map in Scala.

// Method 1

// Empty hash table whose keys are strings and values are integers:
val people: Map[String,Int] = Map()
// Method 2

// A map with keys and values.
val people = Map("Michael" -> 25, "Ross" -> 27, "Ali" -> 21)

Code

In the following code, we explore maps in Scala. Specifically, we look at the commonly used methods of maps:

  • keys: used to access all the keys inside the map
  • values: used to access all the values inside the map
  • ++: used to combine two maps into one
  • isEmpty: used to check whether the map is empty or not, returning a boolean value
object Main extends App {
val people = Map(
    "Michael" -> "25", 
    "Ross" -> "27", 
    "Ali" -> "21"
    )
    // check if map is empty
    println("Is the Map empty? ", people.isEmpty)
    println( "Keys : " + people.keys )
    println( "Values : ")
    people.values.foreach(println)

    // Iterating each key-value pair
    people.keys.foreach{ i =>  
    print( "Key = " + i )
    println(", Value = " + people(i))
    }

    // We can also access indivdual values based on keys.
    println(people("Michael"))

    // one can join two maps using ++ operator
    println("Joining two maps together")
    val people1 = Map(
    "Andrew" -> "33", 
    "Indiana" -> "54", 
    "Peter" -> "12"
    )

    val people2 = people ++ people1
    people2.keys.foreach{ i =>  
    print( "Key = " + i )
    println(", Value = " + people2(i))
    }


}

RELATED TAGS

scala
maps

CONTRIBUTOR

Sarvech Qadir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring