How to change the Map Key with another Key's Value of Same Map in Scala.

Hi Friends,

Today I'd like to show that how we can change or update the key of a Map Value with another key's value of Same Map.

In this below example I'll change the key rplc_key with value of key obj_class.



Input Map :
Map(obj_class -> Hardware, A -> 1, rplc_key -> Map(No -> 1, Status -> Fine)


Output Map :
Map(obj_class -> Hardware, A -> 1, Hardware -> Map(No -> 1, Status -> Fine)


Below is the Code :

object UpdateMapKey extends App {

  //Creating Input Map
   val inputMap: scala.collection.immutable.Map[Any,Any] = Map("obj_class" -> "Hardware", "A" -> "1", "rplc_key" -> Map("No" -> "1", "Status" -> "Fine"))
  println(inputMap)

  //Updating Map Key with Value of another Key
  val outputMapWithUpdatedKey = (inputMap ++ Map((inputMap.get("obj_class").getOrElse(None), inputMap.get("rplc_key").getOrElse(None)))).-("rplc_key")
  println(outputMapWithUpdatedKey)

}


Output Map :




I Hope, This post was helpful, please do like, comment and share.  

Thank You!

Comments

Popular posts from this blog

Transformations and Actions in Spark

How to Convert a Spark DataFrame to Map in Scala

How to Handle and Convert DateTime format in Spark-Scala.