1

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

Mario Galic
  • 47,285
  • 6
  • 56
  • 98
Ajay
  • 177
  • 9
  • What have you tried? Why it didn't work? Did you check out the [**Scaladoc**](https://www.scala-lang.org/api/current/scala/collection/immutable/Map.html)? Have you even made any basic scala tutorial? - Hint you need `filter` + `keys`. – Luis Miguel Mejía Suárez Jul 03 '20 at 18:23
  • @LuisMiguelMejíaSuárez This is what I've done. Not sure if this is the most elegant way of doing it `typeMap.filter(x => !x._2.contains("a.")).keys.toList` – Ajay Jul 03 '20 at 18:44
  • 2
    Yeah that is fine. You may also do this to be a little bit more efficient: `typeMap.view.filterNot { case (_, value) => value.startsWith("a.") }.keysIterator.toList` – Luis Miguel Mejía Suárez Jul 03 '20 at 18:47

1 Answers1

2

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
Mario Galic
  • 47,285
  • 6
  • 56
  • 98