Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to remove elements from a scala mutable map using a predicate

How to do that without creating any new collections? Is there something better than this?

val m = scala.collection.mutable.Map[String, Long]("1" -> 1, "2" -> 2, "3" -> 3, "4" -> 4)
m.foreach(t => if (t._2 % 2 == 0) m.remove(t._1))
println(m)

P.S. in Scala 2.8

like image 431
Oleg Galako Avatar asked Mar 23 '10 14:03

Oleg Galako


People also ask

What is Scala collection mutable map?

Scala map is a collection of key/value pairs. Any value can be retrieved based on its key. Keys are unique in the Map, but values need not be unique. Maps are also called Hash tables. There are two kinds of Maps, the immutable and the mutable.

How do you delete a map in Scala?

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.

Which of the following method can be used to add replace an element from a map in Scala?

Solution. Add elements to a mutable map by simply assigning them, or with the += method.

How can we convert mutable map to immutable Scala?

If you just want a mutable HashMap , you can just use x. toMap in 2.8 or collection. immutable. Map(x.


2 Answers

retain does what you want. In 2.7:

val a = collection.mutable.Map(1->"one",2->"two",3->"three")
a: scala.collection.mutable.Map[Int,java.lang.String] = 
  Map(2 -> two, 1 -> one, 3 -> three)

scala> a.retain((k,v) => v.length < 4)   

scala> a
res0: scala.collection.mutable.Map[Int,java.lang.String] =
  Map(2 -> two, 1 -> one)

It also works, but I think is still in flux, in 2.8.

like image 81
Rex Kerr Avatar answered Oct 03 '22 22:10

Rex Kerr


Per the Scala mutable map reference page, you can remove a single element with either -= or remove, like so:

val m = scala.collection.mutable.Map[String, Long]("1" -> 1, "2" -> 2, "3" -> 3, "4" -> 4)
m -= "1" // returns m
m.remove("2") // returns Some(2)

The difference is that -= returns the original map object, while remove returns an Option containing the value corresponding to the removed key (if there was one.)

Of course, as other answers indicate, if you want to remove many elements based on a condition, you should look into retain, filter, etc.

like image 32
Jonathan Stray Avatar answered Oct 03 '22 23:10

Jonathan Stray