简体   繁体   中英

Nested map iterator in scala

I'm have Nested Map output in my code like below

Map(test -> 113123, "cat" -> None, myList -> Map(test2 -> 321323, test3 -> 11122))

But I wanted output like below using scala iterator if anyone knows please help me on this as I'm very new Scala

Map(test -> 113123, "cat" -> None, myList -> Some(Map(test2 -> 321323, test3 -> 11122)))

Supposing that you have data like

val data = Map("test" -> 113123, "cat" -> None, "myList" -> Map("test2" -> 321323, "test3" -> 11122))
//data: scala.collection.immutable.Map[String,Any] = Map(test -> 113123, cat -> None, myList -> Map(test2 -> 321323, test3 -> 11122))

Then you can do

val output = data.map(x => if (x._2.isInstanceOf[Map[String, Long]]) (x._1 -> Some(x._2)) else x)
//output: scala.collection.immutable.Map[String,Any] = Map(test -> 113123, cat -> None, myList -> Some(Map(test2 -> 321323, test3 -> 11122)))

to get your desired output

And you can use println to see the output as

println(output)
//Map(test -> 113123, cat -> None, myList -> Some(Map(test2 -> 321323, test3 -> 11122)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM