Example of scala MultiMap where the entry types differ

Go To StackoverFlow.com

1

I'd like to have different types of entries for a single Long key.

So given I have a key of 1 I'd like to have the following entries:

1, "dog"
1, 3

First of all is it possible to contain entries of both String and Int types and if so, can I see an example of a HashMap with MultiMap mixed in showing how to add the entries and then access only the "dog" entry?

Thanks!

2012-05-15 13:36
by Sean W


4

If you want your map to contain a mixture of two types of entries, you can use an Either. Either is like Option except that instead of having Some vs. None you have Left vs. Right.

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

val m = new HashMap[Int, Set[Either[Int, String]]] with MultiMap[Int, Either[Int, String]]

m.addBinding(1, Right("dog"))
m.addBinding(1, Left(3))

m(1).collect{ case Right(s) => s }             // Set(dog)
m.mapValues(_.collect{ case Right(s) => s })   // Map(1 -> Set(dog))
2012-05-15 14:39
by dhg
Very cool, thanks - Sean W 2012-05-15 15:28
Ads