How to get the value of a scala map when the key is a tuple where only the first element is known?

Suppose I have scala immutable Map[(String, Boolean), Set[String]]

, for example:

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

      

Now suppose that I know only the first element of a key tuple "a"

. Can (and how if yes) I get the map value for this key if:

1) I know the key can be either ("a", true)

or ("a", false)

(there can be no two keys with the same string as the first element)

2) I don't know that in this case I want to get some kind of concatenation with the possible two values ​​like v1.union(v2)

or v1 ++ v2

etc.

Is there a scala "magic" I could use for example myMap.get(("a", Any))

?

+3


source to share


3 answers


myMap.collect {
  case (("a",b), s) => s
}.toSet.flatten

      

UPDATED (view comments):



If myMap

rather large, you can try:

Set(myMap.get("a", true), myMap.get("a", false)).flatten.flatten

      

+6


source


In general, hash maps don't work that way, at least not efficiently - you can still scan the map linearly and pick the first key that meets the criteria. In your specific case, you can simply try to search twice - first with (key, true)

, then if nothing is found(key, false)



+8


source


If you have a lot of such requests, it might be a good idea to replace the card with Map[String, Map[Boolean, Set[String]]

. It is easy to see that they are equivalent: when you have, for example, ("a", false) -> Set()

and ("a", true) -> Set("a")

on your original map, you will have "a" -> Map(false -> Set(), true -> Set("a"))

in a new one.

This will most likely be less memory efficient, especially with these key types. You can improve this by replacing Map[Boolean, Set[String]]

with (Option[Set[String]], Option[Set[String]])

where the first field matches false

and the second matches true

.

When

1) I know the key can be ("a", true) or ("a", false) (there can be no two keys with the same string as the first element)

just use Map[String, (Boolean, Set[String])]

.

+3


source







All Articles