scalascala-collections

Scala nested map filter


I'm having a nested map which contains both map as well as a combination of List and None value like this

Map(
  test -> 113123, 
  "cat" -> None,
  crm -> List(age, gender, code), 
  myList -> Map(
    test2 -> 321323, 
    test3 -> 11122,
  )
)

But I wanted to filter out non-map values from an above-nested map

expected output:

Map(
  myList -> Map(
    test2 -> 321323,
    test3 -> 11122,
  )
)

Solution

  • collect is your friend whenever you want to do something involving filtering a collection in a way that involves restricting to a certain type:

    val map : Map[Any, Any] = Map(...)
    
    map.collect {
      case (key, map: Map[_, _]) => (key, map)
    }.toMap