0

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,
  )
)
1
  • Please note that I'm reading above value from JSON and parsing it using JSON parser Commented Jun 29, 2018 at 12:20

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

5 Comments

I wanted output like this Map( myList -> Map(test2 -> 321323, test3 -> 11122)) but above code returning List (Key,map(key->value), please help me on this since im very new to scala
I mean it's returning List(myList , Map(test2 -> 321323, test3 -> 11122)) but i wanted Map(myList -> Map(test2 -> 321323, test3 -> 11122))
Ah, whoops - you need to explicitly call .toMap afterwards to get it back to a Map object. I've just edited my answer to add that.
I'm getting compile time exception for this val finalMappingValues= parsedJson.collect { case (key, map: Map[_, _]) => (key, map) }.toMap
I wanted to filter out based on key name like - List(age, gender, code) please any on help me on this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.