Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set and get keys from scala TreeMap?

Tags:

scala

treemap

Suppose I have

import scala.collection.immutable.TreeMap

val tree = new TreeMap[String, List[String]]

Now after above declaration, I want to assign key "k1" to List("foo", "bar") and then how do i get or read back the key "k1" and also read back non-existent key "k2"?

what happens if I try to read non-existent key "k2" ?

like image 613
ace Avatar asked Jun 21 '11 09:06

ace


People also ask

How do I get TreeMap keys?

The process is divided into three steps: Use the entrySet() method of the TreeMap class to get a Set view of all the entries stored in the TreeMap object. Convert the entry set to an array using the toArray() method. And get TreeMap key or TreeMap value using index with the help of getKey() and getValue() method.

How do you access map elements in Scala?

Scala Map get() method with exampleThe get() method is utilized to give the value associated with the keys of the map. The values are returned here as an Option i.e, either in form of Some or None. Return Type: It returns the keys corresponding to the values given in the method as argument.

How do I get TreeMap value?

util. TreeMap. get() method of TreeMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.

Is TreeMap sorted by key?

A TreeMap is always sorted based on keys. The sorting order follows the natural ordering of keys. You may also provide a custom Comparator to the TreeMap at the time of creation to let it sort the keys using the supplied Comparator. A TreeMap cannot contain duplicate keys.


1 Answers

The best way to "mutate" the immutable map is by referring to it in a variable (var as opposed to val):

var tree = TreeMap.empty[String, List[String]]
tree += ("k1" -> List("foo", "bar")) //a += b is sugar for "c = a + b; a = c"

It can be accessed directly using the apply method, where scala syntactic sugar kicks in so you can just access using parens:

val l = tree("k1") //equivalent to tree.apply("k1")

However, I rarely access maps like this because the method will throw a MatchError is the key is not present. Use get instead, which returns an Option[V] where V is the value-type:

val l = tree.get("k1") //returns Option[List[String]] = Some(List("foo", "bar"))
val m = tree.get("k2") //returns Option[List[String]] = None

In this case, the value returned for an absent key is None. What can I do with an optional result? Well, you can make use of methods map, flatMap, filter, collect and getOrElse. Try and avoid pattern-matching on it, or using the Option.get method directly!

For example:

val wordLen : List[Int] = tree.get("k1").map(l => l.map(_.length)) getOrElse Nil

EDIT: one way of building a Map without declaring it as a var, and assuming you are doing this by transforming some separate collection, is to do it via a fold. For example:

//coll is some collection class CC[A]
//f : A => (K, V)
val m = (TreeMap.empty[K, V] /: coll) { (tree, c) => tree + f(c) }

This may not be possible for your use case

like image 188
oxbow_lakes Avatar answered Oct 03 '22 07:10

oxbow_lakes