
- 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 - 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 Collections
- Scala - Collections
- Mutable and Immutable Collections
- Scala - Lists
- Scala - Sets
- Scala - Maps
- Scala - TreeMap
- Scala - SortedMap
- Scala - Tuples
- Scala - Iterators
- Scala - Options
- Scala - Infinite Streams
- Scala - Parallel Collections
- Scala - Algebraic Data Types
- Scala Pattern Matching
- Scala - Pattern Matching
- Scala - Type Patterns
- Scala - Exception Handling
- Scala - Extractors
- Scala - Regular Expressions
- Scala Files I/O
- Scala - Files I/O
- 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 - Literal Type Arithmetic
- Scala - Inline keyword
- Scala - Def, Var & Val
- Scala - Dropped Features
- Scala - BDD Testing
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)