[scala] What is the syntax for adding an element to a scala.collection.mutable.Map?

What is the syntax for adding an element to a scala.collection.mutable.Map ?

Here are some failed attempts:

val map = scala.collection.mutable.Map

map("mykey") = "myval"

map += "mykey" -> "myval"

map.put("mykey","myval")

This question is related to scala map add mutable put

The answer is


Create a new immutable map:

scala> val m1 = Map("k0" -> "v0")   
m1: scala.collection.immutable.Map[String,String] = Map(k0 -> v0)

Add a new key/value pair to the above map (and create a new map, since they're both immutable):

scala> val m2 = m1 + ("k1" -> "v1")             
m2: scala.collection.immutable.Map[String,String] = Map(k0 -> v0, k1 -> v1)

As always, you should question whether you truly need a mutable map.

Immutable maps are trivial to build:

val map = Map(
  "mykey" -> "myval",
  "myotherkey" -> "otherval"
)

Mutable maps are no different when first being built:

val map = collection.mutable.Map(
  "mykey" -> "myval",
  "myotherkey" -> "otherval"
)

map += "nextkey" -> "nextval"

In both of these cases, inference will be used to determine the correct type parameters for the Map instance.

You can also hold an immutable map in a var, the variable will then be updated with a new immutable map instance every time you perform an "update"

var map = Map(
  "mykey" -> "myval",
  "myotherkey" -> "otherval"
)

map += "nextkey" -> "nextval"

If you don't have any initial values, you can use Map.empty:

val map : Map[String, String] = Map.empty //immutable
val map = Map.empty[String,String] //immutable
val map = collection.mutable.Map.empty[String,String] //mutable

The point is that the first line of your codes is not what you expected.

You should use:

val map = scala.collection.mutable.Map[A,B]()

You then have multiple equivalent alternatives to add items:

scala> val map = scala.collection.mutable.Map[String,String]()
map: scala.collection.mutable.Map[String,String] = Map()


scala> map("k1") = "v1"

scala> map
res1: scala.collection.mutable.Map[String,String] = Map((k1,v1))


scala> map += "k2" -> "v2"
res2: map.type = Map((k1,v1), (k2,v2))


scala> map.put("k3", "v3")
res3: Option[String] = None

scala> map
res4: scala.collection.mutable.Map[String,String] = Map((k3,v3), (k1,v1), (k2,v2))

And starting Scala 2.13:

scala> map.addOne("k4" -> "v4")
res5: map.type = HashMap(k1 -> v1, k2 -> v2, k3 -> v3, k4 -> v4)

Create a mutable map without initial value:

scala> var d= collection.mutable.Map[Any, Any]()
d: scala.collection.mutable.Map[Any,Any] = Map()

Create a mutable map with initial values:

scala> var d= collection.mutable.Map[Any, Any]("a"->3,1->234,2->"test")
d: scala.collection.mutable.Map[Any,Any] = Map(2 -> test, a -> 3, 1 -> 234)

Update existing key-value:

scala> d("a")= "ABC"

Add new key-value:

scala> d(100)= "new element"

Check the updated map:

scala> d
res123: scala.collection.mutable.Map[Any,Any] = Map(2 -> test, 100 -> new element, a -> ABC, 1 -> 234)

var map:Map[String, String] = Map()

var map1 = map + ("red" -> "#FF0000")

println(map1)


var test = scala.collection.mutable.Map.empty[String, String]
test("myKey") = "myValue"

When you say

val map = scala.collection.mutable.Map

you are not creating a map instance, but instead aliasing the Map type.

map: collection.mutable.Map.type = scala.collection.mutable.Map$@fae93e

Try instead the following:

scala> val map = scala.collection.mutable.Map[String, Int]()
map: scala.collection.mutable.Map[String,Int] = Map()

scala> map("asdf") = 9

scala> map
res6: scala.collection.mutable.Map[String,Int] = Map((asdf,9))

Examples related to scala

Intermediate language used in scalac? Why does calling sumr on a stream with 50 tuples not complete Select Specific Columns from Spark DataFrame Joining Spark dataframes on the key Provide schema while reading csv file as a dataframe how to filter out a null value from spark dataframe Fetching distinct values on a column using Spark DataFrame Can't push to the heroku Spark - Error "A master URL must be set in your configuration" when submitting an app Add jars to a Spark Job - spark-submit

Examples related to map

Using array map to filter results with if conditional In Java 8 how do I transform a Map<K,V> to another Map<K,V> using a lambda? UnmodifiableMap (Java Collections) vs ImmutableMap (Google) Convert JSONObject to Map Convert Map<String,Object> to Map<String,String> iterate through a map in javascript Iterator over HashMap in Java Simple dictionary in C++ Create Map in Java Map with Key as String and Value as List in Groovy

Examples related to add

Add a new item to recyclerview programmatically? momentJS date string add 5 days How to add an object to an ArrayList in Java ListView with Add and Delete Buttons in each Row in android How to add new column to MYSQL table? How to add text to an existing div with jquery Datetime in C# add days How to add hours to current time in python How To Add An "a href" Link To A "div"? How to use ArrayList.addAll()?

Examples related to mutable

What is difference between mutable and immutable String in java Immutable vs Mutable types What is the syntax for adding an element to a scala.collection.mutable.Map? Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

Examples related to put

How to send a POST request with BODY in swift Use of PUT vs PATCH methods in REST API real life scenarios Laravel form html with PUT method for PUT routes What is the main difference between PATCH and PUT request? Curl and PHP - how can I pass a json through curl by PUT,POST,GET Test file upload using HTTP PUT method PHP cURL HTTP PUT What is the syntax for adding an element to a scala.collection.mutable.Map? How to send a PUT/DELETE request in jQuery? How to send PUT, DELETE HTTP request in HttpURLConnection?