Scala: Using HashMap with a default value

48,520

Solution 1

Try this:

import collection.mutable.HashMap
val x = new HashMap[Int,String]()  { override def default(key:Int) = "-" }
x += (1 -> "b", 2 -> "a", 3 -> "c")

Then:

scala> x(1)
res7: String = b

scala> x(2)
res8: String = a

scala> x(3)
res9: String = c

scala> x(4)
res10: String = -

Solution 2

Wow, I happened to visit this thread exactly one year after I posted my last answer here. :-)

Scala 2.9.1. mutable.Map comes with a withDefaultValue method. REPL session:

scala> import collection.mutable
import collection.mutable

scala> mutable.Map[Int, String]().withDefaultValue("")
res18: scala.collection.mutable.Map[Int,String] = Map()

scala> res18(3)
res19: String = ""

Solution 3

scala> val x = HashMap(1 -> "b", 2 -> "a", 3 -> "c").withDefaultValue("-")
x: scala.collection.immutable.Map[Int,java.lang.String] = Map((1,b), (2,a), (3,c))

scala> x(3)
res0: java.lang.String = c

scala> x(5)
res1: java.lang.String = -

EDIT:

For mutable.HashMap, you could do the following:

scala> import collection.mutable
import collection.mutable

scala> val x = new mutable.HashMap[Int, String] {
     |   override def apply(key: Int) = super.get(key) getOrElse "-"
     | }
x: scala.collection.mutable.HashMap[Int,String] = Map()

scala> x += (1 -> "a", 2 -> "b", 3 -> "c")
res9: x.type = Map((2,b), (1,a), (3,c))

scala> x(2)
res10: String = b

scala> x(4)
res11: String = -

There might be a better way to do this. Wait for others to respond.

Share:
48,520
Admin
Author by

Admin

Updated on September 06, 2020

Comments

  • Admin
    Admin over 3 years

    I have a mutable HashMap and would like to use it like a default-dictionary. The obvious method appears to be to use getOrElse and provide the default value each time as a second value. However this seems a little inelegant in my use case since the default value doesn't change.

    var x = HashMap(1 -> "b", 2 -> "a", 3 -> "c")
    
    println(x.getOrElse(4, "_")
    println(x.getOrElse(5, "_"))
    // And so on...
    println(x.getOrElse(10, "_"))
    

    Is there any way to create a HashMap (or similar class) such that attempting to access undefined keys returns a default value set on the creation of the HashMap? I notice that HashMap.default is just set to throw an exception but I wonder if this can be changed...