0

I have a map of key value pairs and I am trying to fetch the value given a key, however although it returns me a value it comes along with some, any idea how can I get rid of it? My code is:

val jsonmap = simple.split(",\"").toList.map(x => x.split("\":")).map(x => Tuple2(x(0), x(1))).toMap
val text = jsonmap.get("text")

Where "text" is the key and I want the value that it is mapped to, I am currently getting the following output:

Some("4everevercom")    

I tried using flatMap instead of Map but it doesn't work either

0

4 Answers 4

5

You are looking for the apply method. Seq, Set and Map implement different apply methods, the difference being the main distinction between each one.

As a syntactic sugar, .apply can be omitted in o.apply(x), so you'd just have to do this:

val text = jsonmap("text") // pass "key" to apply and receive "value"

For Seq, apply takes an index and return a value, as you used in your own example:

x(0), x(1)

For Set, apply takes a value, and returns a Boolean.

Sign up to request clarification or add additional context in comments.

Comments

4

You can use getOrElse, as @Brian stated, or 'apply' method and deal with absent values on your own:

val text: String = jsonmap("text")
// would trow java.util.NoSuchElementException, if no key presented

Moreover, you can set some default value so Map can fallback to it, if no key found:

val funkyMap = jsonmap.get("text").withDefaultValue("")
funkyMap("foo")
// if foo or any other key is not presented in map, "" will be returned

Use it, if you want to have default value for all missing keys.

Comments

3

You can use getOrElse which gets the value of Some if there is one or the default value that you specify. If the key exists in the map, you will get the value from Some. If the key does not exist, you will get the value specified.

scala> val map = Map(0 -> "foo")
map: scala.collection.immutable.Map[Int,String] = Map(0 -> foo)

scala> map.get(0)
res3: Option[String] = Some(foo)

scala> map.getOrElse(1, "bar")
res4: String = bar

Also, see this for info on Scala's Some and None Options: http://www.codecommit.com/blog/scala/the-option-pattern

Comments

0

Just offering additional options that might help you work with Option and other similar structures you'll find in the standard library.

You can also iterate (map) over the Option. This works since Option is an Iterable containing either zero or one element.

myMap.get(key) map { value =>
  // use value...
}

Equivalently, you can use a for if you feel it makes for clearer code:

for (value <- myMap.get(key)) {
  // use value...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.