I have the following code snippet:
val map = new LinkedHashMap[String,String]
map.put("City","Dallas")
println(map.get("City"))
This outputs Some(Dallas)
instead of just Dallas
. Whats the problem with my code ?
Thank You
Scala Map Function also is known as HASH TABLE is a collection of Key/Value pairs called as Hash Tables. The Key is used to access the values associated with it. Values in a Map can be the same but keys are always unique.
isEmpty: This Scala map method returns true if the map is empty otherwise this returns false. Values can be accessed using Map variable name and key. If we try to access value associated with the key “John”, we will get an error because no such key is present in the Map.
values: Value method returns an iterable containing each value in the Scala map. isEmpty: This Scala map method returns true if the map is empty otherwise this returns false. Values can be accessed using Map variable name and key.
// Mutable variable = scala.collection.mutable.Map (key_1 -> value_1, key_2 -> value_2, key_3 -> value_3, ....) There are three basic operations we can carry out on a Map: keys: In Scala Map, This method returns an iterable containing each key in the map.
Use the apply
method, it returns directly the String
and throws a NoSuchElementException
if the key is not found:
scala> import scala.collection.mutable.LinkedHashMap
import scala.collection.mutable.LinkedHashMap
scala> val map = new LinkedHashMap[String,String]
map: scala.collection.mutable.LinkedHashMap[String,String] = Map()
scala> map.put("City","Dallas")
res2: Option[String] = None
scala> map("City")
res3: String = Dallas
It's not really a problem.
While Java's Map version uses null
to indicate that a key don't have an associated value, Scala's Map[A,B].get
returns a Options[B]
, which can be Some[B]
or None
, and None plays a similar role to java's null
.
REPL session showing why this is useful:
scala> map.get("State")
res6: Option[String] = None
scala> map.get("State").getOrElse("Texas")
res7: String = Texas
Or the not recommended but simple get
:
scala> map.get("City").get
res8: String = Dallas
scala> map.get("State").get
java.util.NoSuchElementException: None.get
at scala.None$.get(Option.scala:262)
Check the Option documentation for more goodies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With