Reputation: 555
Which one is better way to get values from a hashmap?
First Option:
val hm = HashMap(...)
if(hm.contains(keyWhichIsDefinitelyInTheKeys)){
hm(keyWhichIsDefinitelyInTheKeys) ... //do stuff
} else {
... //do stuff
}
Second Option:
hm.get(keyWhichIsDefinitelyInTheKeys) match {
case Some => ...
case None => ...
} // do stuff
Upvotes: 2
Views: 7910
Reputation: 850
In performance:
There is a test code: http://pastebin.com/TbM82S7H
That is its output: http://pastebin.com/7An1DZw5
(cpu: i5 4590K)
None of the two call is better in performance...
Upvotes: 1
Reputation: 22374
This is better for some key:
hm.getOrElse(key, defaultValue)
//or
hm.getOrElse(key, sys.error(s"unexpected key: $key"))
//or more generally
hm.get(key).map(v => doStuff(v)).getOrElse(doOtherStuff)
You can't be 100% sure that Map
contains key, except some type-level protection (compile-time check); however, if you do then if
won't help you eitherway, so just:
hm(keyWhichIsDefinitelyInTheKeys)
Upvotes: 1
Reputation: 49410
As dk14 said, if you are not sure that the Map contains the key, you 'd better use get
which return an Option
.
You can use getOrElse
to set a default value if the key is not present in the Map
.
If you don't have a default value to set, you can use for
comprehension if Option
contains Some
and not a None
scala> val hm = Map( 1 -> "Hello")
hm: scala.collection.immutable.Map[Int,String] = Map(1 -> Hello)
scala> for (i <- hm.get(2) ) { println(i) }
scala> for (i <- hm.get(1) ) { println(i) }
Hello
Upvotes: 3