cool breeze
cool breeze

Reputation: 4811

Remove keys that don't contain any of the values in a set

val s = Set("blue", "orange")
val m = Map("product_orange_123" -> 1, "prodoct_blue_123" -> 2, "product_green_123" -> 5, "product_blue_887" -> 7)

I want to remove any key in the map that doesn't contain any of the values in the set s.

Expected output:

("product_orange_123" -> 1, "prodoct_blue_123" -> 2, "product_blue_887" -> 7)

Upvotes: 1

Views: 309

Answers (2)

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

Set extends Function1

Collect in action

m.collect { case (k, v) if s(k.split("_")(1)) => k -> v }

filterKeys in action

m.filterKeys(key => s(key.split("_")(1)))

filter in action

m.filter { case (k, _) => s(k.split("_")(1)) }

Explanation

Set extends Function1 and set instance can be directly applied to the a key to check if it exists in the set.

scala> val s = Set("blue", "orange")
s: scala.collection.immutable.Set[String] = Set(blue, orange)

scala> s("blue")
res0: Boolean = true

scala> s("apple")
res1: Boolean = false

scala> val s = Set("blue", "orange")
s: scala.collection.immutable.Set[String] = Set(blue, orange)

scala> val m = Map("product_orange_123" -> 1, "prodoct_blue_123" -> 2, "product_green_123" -> 5, "product_blue_887" -> 7)
m: scala.collection.immutable.Map[String,Int] = Map(product_orange_123 -> 1, prodoct_blue_123 -> 2, product_green_123 -> 5, product_blue_887 -> 7)

scala> m.collect { case (k, v) if s(k.split("_")(1)) => k -> v }
res2: scala.collection.immutable.Map[String,Int] = Map(product_orange_123 -> 1, prodoct_blue_123 -> 2, product_blue_887 -> 7)

scala> m.filterKeys(key => s(key.split("_")(1)))
res3: scala.collection.immutable.Map[String,Int] = Map(product_orange_123 -> 1, prodoct_blue_123 -> 2, product_blue_887 -> 7)

scala> m.filter { case (k, _) => s(k.split("_")(1)) }
res4: scala.collection.immutable.Map[String,Int] = Map(product_orange_123 -> 1, prodoct_blue_123 -> 2, product_blue_887 -> 7)

Upvotes: 1

Wonpyo Park
Wonpyo Park

Reputation: 311

Well I guess what you meant

Filter keys of map that does not contains any value of the set

m.filterKeys(key => s.exists(key.contains(_)) )

this will do

Upvotes: 5

Related Questions