0

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)))

1 Answer 1

1

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

9 Comments

val output = data.map(x => if (x._2.isInstanceOf[Map[String, Long]]) (x._1 -> Some(x._2)) else x) println(output), i'm not getting any output for this, could you please help me on this
you have to print them or save it in a file.
I want to create the new map from existing map with some value
I wanted output like this : Map(test -> 113123, "cat" -> None, myList -> Some(Map(test2 -> 321323, test3 -> 11122)))
myMap.mapValues { case v@Option => v case v => Some(v) }
|

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.