
- Scala - Home
- Scala - Overview
- Scala - Features
- Scala - Environment Setup
- Scala - Build Tool (SBT)
- Scala - REPL
- Scala - Dot & Dotty
- Scala - Basic Syntax
- Scala - Hello World Program
- Scala - Identifiers
- Scala - Keywords
- Scala - Comments
- Scala - Code Blocks
- Scala - Semicolon
- Scala - Constructs
- Scala - Expressions
- Scala - Input and Output
- Scala - Optional Braces
- Scala - Underscore (_)
- Data Types and Variables
- Scala - Data Types
- Scala - Type Bounds
- Scala - Context Bound
- Scala - Variances
- Scala - Type Hierarchy
- Scala - Variables
- Scala - Variable Scopes
- Scala - Literals
- Scala - Numeric Types
- Scala - Boolean Types
- Scala - Char Type
- Scala - Unit Types
- Scala - Strings
- Scala - Arrays
- Scala - Null Type
- Scala - Nothing
- Scala - Any Type
- Scala - AnyRef Type
- Scala - Unified Types
- Scala - Dates and Times
- Scala - Ranges
- Scala - Multidimensional Arrays
- Scala - WrappedArray
- Scala - StringBuilder
- Scala - String Interpolation
- Scala - StringContext
- Scala - Type Casting
- Scala var vs val
- Scala Operators
- Scala - Operators
- Scala - Rules for Operators
- Scala - Arithmetic Operators
- Scala - Relational Operators
- Scala - Logical Operators
- Scala - Bitwise Operators
- Scala - Assignment Operators
- Scala - Operators Precedence
- Scala - Symbolic Operators
- Scala - Range Operator
- Scala - String Concatenation Operator
- Scala Conditional Statements
- Scala - IF ELSE
- Scala - IF-ELSE-IF-ELSE Statement
- Scala - Nested IF-ELSE Statement
- Scala Loop Statements
- Scala - Loop Statements
- Scala - while Loop
- Scala - do-while Loop
- Scala - Nested Loops
- Scala - for Loop
- Scala - break Statement
- Scala - yield Keyword
- Scala Classes & Objects
- Scala - Classes & Objects
- Scala - Constructors
- Scala - Auxiliary Constructor
- Scala - Primary Constructor
- Scala - This Keyword
- Scala - Nested Classes
- Scala - Getters and Setters
- Scala - Object Private Fields
- Scala - Singleton Object
- Scala - Companion Objects
- Scala - Creating Executable Programs
- Scala - Stateful Object
- Scala - Enumerations
- Scala - Polymorphism
- Scala - Access Modifiers
- Scala - Apply Method
- Scala - Update Methods
- Scala - UnapplySeq Method
- Scala - Inheritance
- Scala - Extending a Class
- Scala - Method Overloading
- Scala - Method Overriding
- Scala - Generic Classes
- Scala - Generic Functions
- Scala - Superclass Construction
- Scala Methods & Functions
- Scala - Methods
- Scala - Functions
- Scala - Methods vs Functions
- Scala - Main Methods
- Scala - Functions Call-by-Name
- Scala - Functions with Named Arguments
- Scala - Function with Variable Arguments
- Scala - Recursion Functions
- Scala - Default Parameter Values
- Scala - Functions without Parameters
- Scala - Implicit Parameters
- Scala - Higher-Order Functions
- Scala - Nested Functions
- Scala - Extension Methods
- Scala - Anonymous Functions
- Partially Applied Functions
- Scala - Lazy Val
- Scala - Pure Function
- Scala - Currying Functions
- Scala - Control Abstractions
- Scala - Corecursion
- Scala - Unfold
- Scala - Tail Recursion
- Scala - Infinite Sequences
- Scala - Dynamic Invocation
- Scala - Lambda Expressions
- Scala - Polymorphic Functions
- Scala Collections
- Scala - Collections
- Mutable and Immutable Collections
- Scala - Lists
- Scala - Sets
- Scala - Maps
- Scala - TreeMap
- Scala - SortedMap
- Scala - Tuples
- Scala - Iterators
- Scala - Options
- Scala - NumericRange
- Scala - Infinite Streams
- Scala - Parallel Collections
- Scala Advanced Types
- Scala - Union Types
- Scala - Intersection Types
- Scala - Type Aliases
- Scala - Structural Types
- Scala - Match Expression
- Scala - Singleton Type Operator
- Scala - Abstract Types
- Scala - Dependent Types
- Scala - Abstract Type Bounds
- Scala - Higher-Kinded Types
- Scala - Opaque Type Alias
- Scala - Path-Dependent Types
- Scala - Type Lambdas
- Scala - Type Inference
- Scala - Algebraic Data Types
- Scala Pattern Matching
- Scala - Pattern Matching
- Scala - Guards
- Scala - Variables in Patterns
- Scala - Type Patterns
- Scala - The Matchable Trait
- Scala - Matching Arrays
- Scala - Matching Lists
- Scala - Matching Tuples
- Scala - Exception Handling
- Scala - Extractors
- Scala - Pattern Bindings
- Scala - Regular Expressions
- Scala - Case Classes
- Scala - Partial Functions
- Scala - Packaging and Imports
- Scala - Implicit Imports
- Scala - Export Clauses
- Scala - Nested Packages
- Scala - Chained Packages
- Scala - Package Objects
- Scala Files I/O
- Scala - Files I/O
- Scala - Writing Files
- Scala - Listing Files
- Scala - Deleting Directories
- Scala - Check File Exists
- Scala Advanced Concepts
- Scala - Closures
- Scala - Futures
- Scala - Promises
- Scala - Traits
- Scala - Trait Mixins
- Scala - Layered Traits
- Scala - Trait Linearization
- Scala - Sealed Traits
- Scala - Transparent Traits
- Scala - Process Management
- Scala - Scaladoc
- Scala - Literal Type Arithmetic
- Scala - Inline keyword
- Scala - Def, Var & Val
- Scala - Dropped Features
- Scala Unit Testing
- Scala - Unit Testing
- Scala - uTest
- Scala - MUnit
- Scala - ScalaTest Runner
- Scala - ScalaMock
- Scala - JUnit
- Scala - Mocking
- Scala - BDD Testing
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)