Updated April 14, 2023
Introduction to Scala HashMap
Scala HashMap is used to store objects and it take the object in the form of key value pair. For every value there should be one key associated with it. Scala collection contains this Hashmap and it is the implementation of MAP. It stores elements in the form of key value pair and if we want to retrieve any value from the hasmap then it can only be retrieved with the help of key. Keys in the map should be unique.
Syntax
var nameOfMap = HashMap("K1"->"V1", "K2"->"V2", "K3"->"V3", "K4"->"V4")
var map = HashMap(“Red” -> “ROSE”, “YEllOW” -> “Car”);
How HashMap works in Scala?
HashMap is the implementation of Map. In Scala map can be of two types which are as follows:
- Mutable
- Immutable
Mutable maps in which if we add object they will be mutable. Immutable map is in which we add object they will be immutable. But in Scala they by default provide as immutable map. The main difference between both these two term is that if the object os immutable then it cannot change the value itself for them. We can also make our map mutable but this we have to do explicitly. by importing scala.collection.mutable.Map class.
var map:HashMap[Int, Char] = HashMap()
Here we are creating an empty map and we are mentioning the type of parameters it will take. In the above case we define integer and character so while insertion it will only allow us to insert integer and character. If we try assigning any other type compile time exception will be thrown.
Methods
Map provide is some methods to retrieve key, value and to check whether the map is empty or not.
- key: This method will give us the list of all the keys which are contain inside the map.
- isEmpty : This method return true or false bases of condition. This method will check whether the map is empty or not if it is empty it will return true otherwise it will return false, this method is very useful when we try to iterate an empty map.
- value: This method will return as the list of values contains in the map.
- contains: This method is used to check whether the key is present in the map or not.
Two Maps in Scala
We can also concatenate two maps in Scala. But after concatenation, it will remove all the duplicate keys present in the result map. For concatenation, we can go for two approach
- Map++
- ++
Code:
import scala.collection.mutable.HashMap;
object Main extends App{
// Your code here!
// Here we are initializing our ap with key and value
val colors = HashMap("ABCt" -> "Hello", "XYZ" -> "Bye","PQR" -> "Lost")
println("Key and Value containing in map :: " + colors)
}
Output:
In this example, we are simply just preparing our map with the desired key and value and printing those values by using the println method available in the scala.
Examples to Implement Scala HashMap
Below are the examples mentioned:
1. Using key method
Code:
import scala.collection.mutable.HashMap;
object Main extends App{
// Your code here!
// Here we are initializing our ap with key and value
val map = HashMap("Amit" -> "001", "Sumit" -> "002", "Aman" -> "003", "Sunita" -> "004", "Amita" -> "005", "Vinata" -> "006", "Komal" -> "007", "Nikita" -> "008")
map.keys.foreach{ k =>
println( "Key in the map is = " + k )
}
}
Output:
2. Reading Values
Code:
import scala.collection.mutable.HashMap;
object Main extends App{
// Your code here!
// Here we are initializing our ap with key and value
val map = HashMap("Amit" -> "001", "Sumit" -> "002", "Aman" -> "003", "Sunita" -> "004", "Amita" -> "005", "Vinata" -> "006", "Komal" -> "007", "Nikita" -> "008")
map.values.foreach{ k =>
println( "Value in the map is = " + k )
}
}
Output:
3. Using isEmpty method
Code:
import scala.collection.mutable.HashMap;
object Main extends App{
// Your code here!
// Here we are initializing our ap with key and value
val map = HashMap("Amit" -> "001", "Sumit" -> "002", "Aman" -> "003", "Sunita" -> "004", "Amita" -> "005", "Vinata" -> "006", "Komal" -> "007", "Nikita" -> "008")
if(map.isEmpty ){
println("Map is empty")
} else{
println("map is not empty :: see keys below :")
println(" ------ ")
map.values.foreach{ k =>
println( "Key in the map is = " + k )
}
}
}
Output:
4. Checking key in map
Code:
import scala.collection.mutable.HashMap;
object Main extends App{
// Your code here!
// Here we are initializing our ap with key and value
val map = HashMap("Amit" -> "001", "Sumit" -> "002", "Aman" -> "003", "Sunita" -> "004", "Amita" -> "005", "Vinata" -> "006", "Komal" -> "007", "Nikita" -> "008")
if(map.contains( "Sumit" ) ){
println("Hello i am sumit here.")
}
if( map.contains( "Nikita" )){
println("Hello i am nikita here.")
}
if(map.contains( "ABC" )){
println("Hello i am abc here.")
} else{
println("Student not found.")
}
}
Output:
5. Two maps using .++ method and ++
Code:
import scala.collection.mutable.HashMap;
object Main extends App{
val map1 = HashMap("Amit" -> "001", "Sumit" -> "002", "Aman" -> "003", "Sunita" -> "004", "Amita" -> "005", "Vinata" -> "006", "Komal" -> "007", "Nikita" -> "008")
val map2 = HashMap("Tarun" -> "001", "Sumit" -> "002", "Aman" -> "003", "shelly" -> "004", "Amita" -> "005", "Madhu" -> "006", "Komal" -> "007", "Megah" -> "008")
val result = map1 ++ map2
println("result map after concatinate by uing ++ method between both map :: " + result)
println("Duplicate keys are removed. :)")
println(" ")
println(" ")
val result2 = map1.++(map2)
println("result2 map after concatinate by uing .++ method :: " + result2)
println("Duplicate keys are removed. :)")
}
Output:
Conclusion
So Hashmap Are used to store our objects in key value format. They are the implementation of map in Scala and work pretty much same as Java maps. Keys have to be unique we can also define data type for key and value to avoid future error.
Recommended Articles
We hope that this EDUCBA information on “Scala HashMap” was beneficial to you. You can view EDUCBA’s recommended articles for more information.