Search code examples
scalahashmaphashtable

scala hashmap multiple values


I would like to implement a hashtable with int keys and string values. I tried the following:

import scala.collection.mutable.HashMap
val test_map = new HashMap[Int, String]
test_map += 10 -> "prog_1"
test_map += 20 -> "prog_2"
test_map += 25 -> "prog_3"
test_map += 15 -> "prog_4"
test_map += 10 -> "prog_8"

However, test_map(10) is not "prog_1", "prog_8", it is just "prog_8". It seems that this hashmap cannot have multiple values. Is there a simple way to have a multi-value hash table in Scala?


Solution

  • You can use a MultiMap if you don't care about preserving insertion order for values with the same key:

    import scala.collection.mutable.{ HashMap, MultiMap, Set }
    
    val test = new HashMap[Int, Set[String]] with MultiMap[Int, String]
    
    test.addBinding(10, "prog_1")
    test.addBinding(20, "prog_2")
    test.addBinding(25, "prog_3")
    test.addBinding(15, "prog_4")
    test.addBinding(10, "prog_8")