
- Scala Collections - Home
- Scala Collections - Overview
- Scala Collections - Environment Setup
- Scala Collections - Arrays
- Scala Collections - Array
- Scala Collections - Multi-Dimensional Array
- Scala Collections - Array using Range
- Scala Collections - ArrayBuffer
- Scala Collections - Lists
- Scala Collections - List
- Scala Collections - ListBuffer
- Scala Collections - ListSet
- Scala Collections - Vector
- Scala Collections - Sets
- Scala Collections - Set
- Scala Collections - BitSet
- Scala Collections - HashSet
- Scala Collections - TreeSet
- Scala Collections - Maps
- Scala Collections - Map
- Scala Collections - HashMap
- Scala Collections - ListMap
- Scala Collections - Miscellaneous
- Scala Collections - Iterator
- Scala Collections - Option
- Scala Collections - Queue
- Scala Collections - Tuple
- Scala Collections - Seq
- Scala Collections - Stack
- Scala Collections - Stream
- Scala Collections Combinator methods
- Scala Collections - drop
- Scala Collections - dropWhile
- Scala Collections - filter
- Scala Collections - find
- Scala Collections - flatMap
- Scala Collections - flatten
- Scala Collections - fold
- Scala Collections - foldLeft
- Scala Collections - foldRight
- Scala Collections - map
- Scala Collections - partition
- Scala Collections - reduce
- Scala Collections - scan
- Scala Collections - zip
- Scala Collections Useful Resources
- Scala Collections - Quick Guide
- Scala Collections - Useful Resources
- Scala Collections - Discussion
Scala Collections - HashMap
Scala map is a collection of key/value pairs. Any value can be retrieved based on its key. Keys are unique in the Map, but values need not be unique. HashMap implements immutable map and uses hash table to implement the same.
Declaring HashMap Variables
The following is the syntax for declaring an HashMap variable.
Syntax
val colors = HashMap("red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F")
Here, colors is declared as an hash-map of Strings, Int which has three key-value pairs. Values can be added by using commands like the following −
Command
var myMap1: HashMap[Char, Int] = colors + ("black" -> "#000000");
Processing HashMap
Below is an example program of showing how to create, initialize and process HashMap −
Example
import scala.collection.immutable.HashMap object Demo { def main(args: Array[String]) = { var myMap: HashMap[String,String] = HashMap( "red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F" ); // Add an element var myMap1: HashMap[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: HashMap[String,String] = myMap - ("white"); // Create empty map var myMap3: HashMap[String,String] = HashMap.empty[String, String]; println(myMap1); println(myMap2); println(myMap3); } }
Save the above program in Demo.scala. The following commands are used 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 HashMap(azure -> #F0FFFF, peru -> #CD853F, white -> #FFFFFF, red -> #FF0000) HashMap(azure -> #F0FFFF, peru -> #CD853F, red -> #FF0000) HashMap()
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.HashMap object Demo { def main(args: Array[String]) = { val colors1 = HashMap( "red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F" ) val colors2 = HashMap( "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 : HashMap(blue -> #0033FF, azure -> #F0FFFF, peru -> #CD853F, yellow -> #FFFF00, red -> #FF0000) colors1.++(colors2)) : HashMap(blue -> #0033FF, azure -> #F0FFFF, peru -> #CD853F, yellow -> #FFFF00, red -> #FF0000)
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.HashMap object Demo { def main(args: Array[String]) = { val colors = HashMap("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 = red Value = #FF0000 Key = azure Value = #F0FFFF Key = peru Value = #CD853F
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 a map -
import scala.collection.immutable.HashMap object Demo { def main(args: Array[String]) = { val colors = HashMap("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 : HashMap(azure -> #F0FFFF, peru -> #CD853F) Map without azure : HashMap(red -> #FF0000, peru -> #CD853F)
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
Try the following example for merging HashMaps -
import scala.collection.immutable.HashMap object Demo { def main(args: Array[String]) = { val map1 = HashMap("A" -> 1, "B" -> 2, "C" -> 3) val map2 = HashMap("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: HashMap(A -> 1, B -> 20, C -> 3, D -> 4) Merged map using ++ method: HashMap(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 even numbers of HashMap -
import scala.collection.immutable.HashMap object Demo { def main(args: Array[String]) = { val scores = HashMap("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: HashMap(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.HashMap object Demo { def main(args: Array[String]) = { val prices = HashMap("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: HashMap(Apple -> 2.25, Orange -> 1.62, Banana -> 1.08)