0
votes

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
2
Thanks for the feedback. Basically, I want to store Map of key-value pair on each element of ArrayBuffer. I have been able to append the map into ArrayBuffer with following ways - JobConfigs += X.toString() JobConfigs += Y.toString() println(JobConfigs) ArrayBuffer(Map(Name -> Raghav, Home -> Gurgaon), Map(Name -> Vikrant, Home -> Noida)) Now I need to iterate over each element of ArrayBuffer; then iterate over Map and print key and values of it. its throwing issue - for (e <- JobConfigs) { for ((k, v) <- e) { println("Key:" + k + ", Value:" + v) } } - Raghavendra Gupta
Will look at basics. So far, working on Python where life is simpler in terms on datatypes. - Raghavendra Gupta
If you want, you can share what do you want to do (all your problem)_and I will provide an answer explaining how you can do that on _idiomatic Scala. Without that much mutability and using correct types. - Luis Miguel Mejía Suárez

2 Answers

1
votes

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:

  1. JobConfigs should be declared as val, unless you later do JobConfigs = .... Even if you do, it's often not a good idea.

  2. Idiomatic names for local variables start with a lower-case letter: x, y, jobConfigs.

0
votes

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