Reputation: 466
How to map id and name to the given sequence in scala ... If suppose I have Input Sequence like this
Seq((1, "teja"), (2, "mahesh"))
and I need to get Output like
Map[("id" ->1 ,"name"->"teja"),("id" ->2,"name"->"mahesh")]
How to do it?
Upvotes: 1
Views: 711
Reputation: 10884
You can do it like this:
scala> Seq((1, "teja"), (2, "mahesh")) map { case (id,name) => ("id" -> id, "name" -> name) }
res0: Seq[((String, Int), (String, String))] = List(((id,1),(name,teja)), ((id,2),(name,mahesh)))
to keep the ->
in the toString use a Map
scala> Seq((1, "teja"), (2, "mahesh")) map { case (id,name) => Map("id" -> id, "name" -> name) }
res1: Seq[scala.collection.immutable.Map[String,Any]] = List(Map(id -> 1, name -> teja), Map(id -> 2, name -> mahesh))
if you need it within a map you can do
scala> Seq((1, "teja"), (2, "mahesh")).map { case (id,name) => ("id" -> id, "name" -> name) }.toMap
res2: scala.collection.immutable.Map[(String, Int),(String, String)] = Map((id,1) -> (name,teja), (id,2) -> (name,mahesh))
then the key will be a Tuple2[String,Int] though.
Upvotes: 2