Ajay
Ajay

Reputation: 198

Scala: Pick items from Map based on a condition

I have the following map

val typeMap = Map(
  "Sample1" -> "a.type1",
  "Sample2" -> "a.type2",
  "Sample3" -> "b.type1",
  "Sample4" -> "b.type2",
  "Sample5" -> "b.type3",
  "Sample6" -> "c.type1",
  "Sample7" -> "c.type2",
  "Sample8" -> "c.type2",
  "Sample9" -> "d.type1"
)

I need to pick all Samples that are not of type "a.XXX"

So my expected output should be a list with values

Sample3, Sample4, Sample5, Sample6, Sample7, Sample8, Sample9

Upvotes: 1

Views: 623

Answers (1)

Mario Galic
Mario Galic

Reputation: 48420

Consider collect with interpolated string patterns

typeMap collect { case (key, s"$x.$y") if x != "a" => key }

As a side-note, in Scala, perhaps confusingly, filter means "filter in" whilst filterNot means "filter out"

typeMap.filter    { case (_, value) => !value.startsWith("a") }.keys  // keep in elements satisfying the condition
typeMap.filterNot { case (_, value) =>  value.startsWith("a") }.keys  // keep out elements satisfying the condition

Upvotes: 2

Related Questions