Is there a shortcut to filter a Map keeping only the entries where the key is contained in a given Set?
Here is some example code
scala> val map = Map("1"->1, "2"->2, "3"->3)
map: scala.collection.immutable.Map[java.lang.String,Int] = Map(1 -> 1, 2 -> 2, 3 -> 3)
scala> map.filterKeys(Set("1","2").contains)
res0: scala.collection.immutable.Map[java.lang.String,Int] = Map(1 -> 1, 2 -> 2)
I am searching for something shorter than this.
Answering the Question
You can take advantage of the fact that a
Set[A]is a predicate; i.e.A => BooleanHere it is at work:
Or if you prefer:
Predicates
It’s actually really useful to have some wrapper around a predicate. Like so:
And an implicit conversion:
And then you can use it:
This can be extended to
xor,nandetc etc and if you include symbolic unicode can make for amazingly readable code: