How do I get a subset of a map?
Assume we have
val m: Map[Int, String] = ...
val k: List[Int]
Where all keys in k
exist in m
.
Now I would like to get a subsect of the Map m
with only the pairs which key is in the list k
.
Something like m.intersect(k)
, but intersect
is not defined on a map.
One way is to use filterKeys
: m.filterKeys(k.contains)
. But this might be a bit slow, because for each key in the original map a search in the list has to be done.
Another way I could think of is k.map(l => (l, m(l)).toMap
. Here wie just iterate through the keys we are really interested in and do not make a search.
Is there a better (built-in) way ?