Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a scala Map value, when the key is a tuple in which only the first element is known?

Tags:

key

tuples

scala

Suppose I have a scala immutable Map[(String, Boolean), Set[String]], e.g.:

val myMap = Map(("a",true) -> Set("b","c"))

Now suppose I only know the first element of the key tuple, "a". Can (and how if yes) I get the map's value for this key if:

1) I know that the key could either be ("a", true) or ("a", false) (there cannot be two keys with the same String as the first element)

2) I don't know that, in which case I wish to get some kind of concatenation on the possible two values, such as v1.union(v2) or v1 ++ v2, etc.

Is there any scala "magic" I could use, like myMap.get(("a", Any))?

like image 919
Giora Simchoni Avatar asked Dec 02 '22 14:12

Giora Simchoni


1 Answers

In general, hash maps does not work like that, at least efficiently -- you still can scan map linearly and pick first key that matches criteria. In your particular case you can simply try to lookup record twice -- first with (key, true), then if nothing is found (key, false)

like image 67
om-nom-nom Avatar answered Dec 18 '22 09:12

om-nom-nom