Lang : SCALA
I have one map
defined in my properties files as:
dummy {
"Key1" : ["value1","value2", "value3"]
"Key2" : ["Hi1", "Hi2"]
"Key3" : ["Bye1"]
}
Now, I could find entryset
for above map
and fill it in scala's map
as:
var configTrialMap: Config = config.getConfig("dummy")
val resMap = mutable.Map[String, List[String]]()
for (entry <- configTrialMap.entrySet.asScala) {
resMap.put(entry.getKey, entry.getValue.unwrapped().toString.split(",").map(_.trim).toList)
}
But problem is this code looks clumsy and I have to put some regex to replace all [, ]
with blank character
I have seen some solutions to convert java collection to scala one but none of them seem to be working since unwrapped()
return an Object
instance and I have to cast it first.
I have tried playing with:
asScalaBuffer
(https://alvinalexander.com/scala/how-to-go-from-java-collections-convert-in-scala-interact)
val javaToScalaList = entry.getValue.unwrapped().asInstanceOf[List[String]]
.asScala.toList
Sorry, if it is too naive. I am new to scala.
You can do:
import com.typesafe.config.ConfigFactory
import scala.collection.JavaConverters._
//load config into configTrialMap
configTrialMap.getObject("dummy")
.keySet().asScala
.map(k => {
val k2 = k.replaceAll("\\.", "\".\"") //quote all the dots in key
("dummy."+k2, configTrialMap.getStringList(s"dummy." + k2).asScala.toList)
})
.toMap
which results in:
scala.collection.immutable.Map[String,List[String]] = Map(dummy.U"."S"." Sample -> List(Bye1), dummy.Key2 -> List(Hi1, Hi2), dummy.Key1 -> List(value1, value2, value3))
EDIT: (to add regex replacement to fix paths with dots)
To handle dots in keys, you need to quote them using "
character. I have updated the answer with a regex that does this.