I have stored my key, value pairs in multiple Mutable Map with MapString, String. And I can see the key and values in it. However, now I need to append these maps onto ArrayBuffer or List with String Type in Scala. So that, I can loop over every element in Array and proceed further. Please help.
Sample Code.
val X= scala.collection.mutable.Map[String, String]()
X += ("Name" -> "Raghav")
X += ("Home" -> "Gurgaon")
val Y= scala.collection.mutable.Map[String, String]()
Y += ("Name" -> "Vikrant")
Y += ("Home" -> "Noida")
var JobConfigs = scala.collection.mutable.ArrayBuffer.empty[String]
JobConfigs += X
JobConfigs += Y
From your comment:
its throwing issue -
for (e <- JobConfigs) { for ((k, v) <- e) { println("Key:" + k + ", Value:" + v) } }
This doesn't make sense; because your JobConfigs
is an ArrayBuffer[String]
, e
will be a String
and doesn't contain any pairs. It will work, with no other changes, if you change the type of JobConfigs
:
var JobConfigs = scala.collection.mutable.ArrayBuffer.empty[Map[String, String]]
Alternatively, you could have
var JobConfigs = scala.collection.mutable.ArrayBuffer.empty[(String, String)]
JobConfigs ++= X
JobConfigs ++= Y
for ((k, v) <- JobConfigs) { println("Key:" + k + ", Value:" + v) }
Side notes:
JobConfigs
should be declared as val
, unless you later do JobConfigs =...
. Even if you do, it's often not a good idea.
Idiomatic names for local variables start with a lower-case letter: x
, y
, jobConfigs
.
The following code will add an immutable object of Map to ArrayBuffer.
JobConfigs += X
You can try to insert an mutable object like this:
JobConfigs.append(X.toMap)
Not sure why you want to convert the map to string, I would suggest you keep it a Map which is better for accessing the values. But here is a snippet to convert a map to String:
Map("ss" -> "yy", "aa" -> "bb").map{case (k, v) => k + ":" + v}.mkString("|")
Hope this helps. Good luck.
Another approach using case classes.
case class Person(Name: String, Home: String)
var JobConfig = scala.collection.mutable.ArrayBuffer[Person]()
JobConfig += Person("Raghav", "Gurgaon")
JobConfig += Person("Vikrant", "Noida")
for(i <- JobConfig){
println(s"home :${i.Home} , name : ${i.Name}")
}
Output:
home :Gurgaon , name : Raghav
home :Noida , name : Vikrant
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.