hispanicprogrammer
hispanicprogrammer

Reputation: 437

Better way to create new key in map if key doesnt exist in Scala?

I have the following list of maps in Scala:

val list =   List(Map( "age" -> 25, "city" -> "London", "last_name" -> "Smith"), 
         Map("city" -> "Berlin", "last_name" -> "Robinson"))

And I wish to iterate through the list of maps and check if the key "age" exists. If it doesnt, I want to create the entry and put it in the map. So far I have tried:

val tmp = list.map( item => if (!item.contains("age")) item.updated("age",5) else item)
print(tmp)

which works fine, I just wanted to know if there is a more efficient way to do it (perhaps with comprehensions or anything else?)! Any advice would be appriciated

Upvotes: 1

Views: 333

Answers (1)

jwvh
jwvh

Reputation: 51271

I'd do it this way.

val newList = 
  list.map{m => if (m.keySet("age")) m else m + ("age" -> "5")}

Note that if you don't make the value 5 a String then the result is a Map[String,Any], which is not what you want.

Upvotes: 1

Related Questions