Scala hashmap multiple values

I am new to Scala and I would like to implement a simple hash table that has int keys and string values.

I tried the following code:

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, the value of test_map (10) is not "prog_1", "prog_8" is just "prog_8". It seems that this hashmap is just a key, a value function that cannot have multiple values. Is there an easy way to have a multi-valued hash table in Scala?

+5
source share
2 answers

You can use MultiMapit if you do not need to keep the 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")
+10
source

MultiMap, HashMap

import scala.collection.mutable.HashMap
import scala.collection.mutable.MultiMap    
import scala.collection.mutable.Set

val test_map = new HashMap[Int, Set[String]] with MultiMap[Int, String]
test_map.addBinding(10 ,"prog_1")
test_map.addBinding(20 ,"prog_2")
test_map.addBinding(25 ,"prog_3")
test_map.addBinding(15 ,"prog_4")
test_map.addBinding(10 ,"prog_8")
+3

All Articles