Scala - TreeMap



Scala TreeMap is a collection of key/value pairs where keys are sorted. Any value can be retrieved based on its key. Keys are unique in the TreeMap, but values need not be unique. TreeMap implements immutable map and uses a tree structure to maintain the sorted order of keys. It is useful when you need a map with sorted keys.

Declaring TreeMap Variables

The following is the syntax for declaring a TreeMap variable.

Syntax

import scala.collection.immutable.TreeMap

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

Here, colors is declared as a TreeMap of String keys and String values, which has three key-value pairs. Values can be added by using commands like the following:

Command

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

Processing TreeMap

Below is an example program showing how to create, initialize, and process a TreeMap.

Example

import scala.collection.immutable.TreeMap

object Demo {
   def main(args: Array[String]) = {
      var myMap: TreeMap[String, String] = TreeMap(
         "red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F"
      )
      // Add an element
      var myMap1: TreeMap[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: TreeMap[String, String] = myMap - "white"
      // Create empty map
      var myMap3: TreeMap[String, String] = TreeMap.empty[String, String]
      println(myMap1)
      println(myMap2)
      println(myMap3)
   }
}

Save the above program in Demo.scala. Use the following commands 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
TreeMap(azure -> #F0FFFF, peru -> #CD853F, red -> #FF0000, white -> #FFFFFF)
TreeMap(azure -> #F0FFFF, peru -> #CD853F, red -> #FF0000)
TreeMap()

Concatenating Maps

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

Example

Try the following example program to concatenate two Maps -

import scala.collection.immutable.TreeMap

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

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

colors1 ++ colors2 : TreeMap(azure -> #F0FFFF, blue -> 
   #0033FF, peru -> #CD853F, red -> #FF0000, yellow -> #FFFF00)
colors1.++(colors2)) : TreeMap(azure -> #F0FFFF, blue -> 
   #0033FF, peru -> #CD853F, red -> #FF0000, yellow -> #FFFF00)

Print Keys and Values from a Map

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

Example

Following is the example program demonstrating how you can print the keys and values from a Map –

import scala.collection.immutable.TreeMap

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

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

Save the above program in Demo.scala. Use the following commands 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

Removing Key-Value Pairs from a Map

You can remove key-value pairs from a Map using the - operator or the Map.-() method. Both methods return a new map with the specified key-value pairs removed.

Example

Try the following example for removing key-value pairs from TreeMap -

import scala.collection.immutable.TreeMap

object Demo {
   def main(args: Array[String]) = {
      val colors = TreeMap("red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F")
      // Remove a key-value pair using the - operator
      val updatedColors1 = colors - "red"
      println("Map without red : " + updatedColors1)
      // Remove a key-value pair using the - method
      val updatedColors2 = colors.-("azure")
      println("Map without azure : " + updatedColors2)
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

Map without red : TreeMap(azure -> #F0FFFF, peru -> #CD853F)
Map without azure : TreeMap(peru -> #CD853F, red -> #FF0000)

Merging Maps

You can merge two maps using the ++ operator or the Map.++() method. Both methods combine the key-value pairs of the maps, with the values from the second map overwriting the values from the first map in case of duplicate keys.

Example

import scala.collection.immutable.TreeMap

object Demo {
   def main(args: Array[String]) = {
      val map1 = TreeMap("A" -> 1, "B" -> 2, "C" -> 3)
      val map2 = TreeMap("B" -> 20, "D" -> 4)
      // Merge two maps using the ++ operator
      val mergedMap1 = map1 ++ map2
      println("Merged map using ++ operator: " + mergedMap1)
      // Merge two maps using the ++ method
      val mergedMap2 = map1.++(map2)
      println("Merged map using ++ method: " + mergedMap2)
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

Merged map using ++ operator: TreeMap(A -> 1, B -> 20, C -> 3, D -> 4)
Merged map using ++ method: TreeMap(A -> 1, B -> 20, C -> 3, D -> 4)

Filtering Maps

You can filter a map based on certain conditions using the filter method. This method returns a new map containing only the key-value pairs that satisfy the predicate function.

Example

Try the following example for filtering maps -

import scala.collection.immutable.TreeMap

object Demo {
   def main(args: Array[String]) = {
      val scores = TreeMap("Alice" -> 100, "Bob" -> 95, "Charlie" -> 85, "David" -> 75)

      // Filter scores where the value is greater than 90
      val highScores = scores.filter { case (_, score) => score > 90 }

      println("High scores: " + highScores)
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

High scores: TreeMap(Alice -> 100, Bob -> 95)

Transforming Maps

You can transform a map by applying a transformation function to each key-value pair using the map method. This method returns a new map with the transformed key-value pairs.

Example

import scala.collection.immutable.TreeMap

object Demo {
   def main(args: Array[String]) = {
      val prices = TreeMap("Apple" -> 2.5, "Orange" -> 1.8, "Banana" -> 1.2)

      // Apply 10% discount to all prices
      val discountedPrices = prices.map { case (fruit, price) => (fruit, price * 0.9) }

      println("Discounted prices: " + discountedPrices)
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

Discounted prices: TreeMap(Apple -> 2.25, Orange -> 1.62, Banana -> 1.08)
Advertisements