Scala - SortedMap



Scala SortedMap 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 SortedMap, but values need not be unique. SortedMap implements an immutable map and uses a tree structure to keep the sorted order of keys. It is used when you need a map with sorted keys.

Declaring SortedMap Variables

The following is the syntax for declaring a SortedMap variable.

Syntax

 import scala.collection.immutable.SortedMap val colors = SortedMap("red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F") 

Here, colors is declared as a SortedMap 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: SortedMap[Char, Int] = colors + ("black" -> "#000000") 

Processing SortedMap

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

Example

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

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.SortedMap object Demo { def main(args: Array[String]) = { val colors1 = SortedMap( "red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F" ) val colors2 = SortedMap( "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 : SortedMap(azure -> #F0FFFF, blue -> #0033FF, peru -> #CD853F, red -> #FF0000, yellow -> #FFFF00) colors1.++(colors2)) : SortedMap(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. Following is the example program.

Example

 import scala.collection.immutable.SortedMap object Demo { def main(args: Array[String]) = { val colors = SortedMap("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 SortedMap -

 import scala.collection.immutable.SortedMap object Demo { def main(args: Array[String]) = { val colors = SortedMap("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 : SortedMap(azure -> #F0FFFF, peru -> #CD853F) Map without azure : SortedMap(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.SortedMap object Demo { def main(args: Array[String]) = { val map1 = SortedMap("A" -> 1, "B" -> 2, "C" -> 3) val map2 = SortedMap("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: SortedMap(A -> 1, B -> 20, C -> 3, D -> 4) Merged map using ++ method: SortedMap(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 SortedMaps -

 import scala.collection.immutable.SortedMap object Demo { def main(args: Array[String]) = { val scores = SortedMap("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: SortedMap(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.SortedMap object Demo { def main(args: Array[String]) = { val prices = SortedMap("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: SortedMap(Apple -> 2.25, Orange -> 1.62, Banana -> 1.08) 
Advertisements