What is the map.remove() method in Scala?

The map.remove() function in Scala removes a specific element, a key-value pair, from the map.

  • If the key is found in the map, the key-value pair is removed and the key is returned.
  • If the key is not found in the map, None is returned.

The illustration below shows a visual representation of the map.remove() function.

Figure 1: Visual representation of map.remove() function

The following module is required in order to use this function: scala.collection.mutable.Map

Syntax

map.remove(key)

map is the name of the queue.

Parameter

The map.remove() function requires a key to remove that specific key-value pair from the map.

Return value

The map.remove() function removes a specific element, a key-value pair, from a map.

Code

The following code shows how to use the map.remove() function in Scala.

import scala.collection.mutable.Map
object Main extends App {
//creating map
val map = scala.collection.mutable.Map(
1 -> "Tom",
2 -> "Alsvin",
3 -> "Eddie"
)
//map containg key value pairs before remove
println("The map elements before remove: " + map);
//map after remove 3rd element
println("The value against 3rd element: " + map.remove(3));
println("The map elements after 3rd element remove: " + map);
//map after remove 0th element which is not present in map
println("The value against 0th element: " + map.remove(0));
println("The map elements after 0 element remove: " + map);
}