Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 707
richsoni Avatar asked Jun 12 '12 21:06

richsoni


People also ask

Can HashMap have multiple values?

HashMap can be used to store key-value pairs. But sometimes you may want to store multiple values for the same key. For example: For Key A, you want to store - Apple, Aeroplane.

How do you store a value on a map?

a) The values can be stored in a map by forming a key-value pair. The value can be retrieved using the key by passing it to the correct method. b) If no element exists in the Map, it will throw a 'NoSuchElementException'. c) HashMap stores only object references.

Can a Key have multiple values in map C++?

The C++ STL also provides a multimap template, which removes the unique key restriction. A single key in a multimap can map to multiple values.


2 Answers

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")
like image 115
Travis Brown Avatar answered Sep 30 '22 07:09

Travis Brown


Use the MultiMap trait, to take a standard mutable HashMap and enhance it with some convenient methods for handling multi-valued maps

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")
like image 36
Dave Griffith Avatar answered Sep 30 '22 08:09

Dave Griffith