3

How to combine two MultiMaps in Scala with a union over the value sets in a nice way?

I currently do (given mm1 and mm2 are MultiMaps with identical type):

val tempmm = (mm1.keySet union mm2.keySet).
               map{k=>(k,(mm1.getOrElse(k,Set()) union mm2.getOrElse(k,Set())))}
tempmm.foreach{case (k,v) => mm1(k)=v}

Now I have the right result in mm1. But I'm sure there must be a nicer way. Probably even a function in MultiMap.

Rick-777
  • 9,714
  • 5
  • 34
  • 50
leo
  • 3,677
  • 7
  • 34
  • 46
  • 1
    http://stackoverflow.com/questions/7755214/scala-merge-maps-by-key might be useful here. Would be nice to see `unionWith`, `intersectionWith` in base Map traits, but the scalaz solution might work in your case. – Impredicative Feb 22 '13 at 13:18

1 Answers1

3

To merge mm2 into mm1, you could do this:

for ( (k, vs) <- mm2; v <- vs ) mm1.addBinding(k, v)
Régis Jean-Gilles
  • 32,541
  • 5
  • 83
  • 97
  • Thanks, that's very nice! Coming from Haskell I sometimes forget about for. I'm still hopping for a even better solution, I guess adding all values one by one might be a bit slow. – leo Feb 22 '13 at 14:51
  • 2
    There's no way to know whether adding them one by one would be slower, just the same, or even faster without a deeper understanding of the underlying algorithms. It's quite possibly the same because that's ultimately what has to happen sooner or later. Performance would need to be measured to be more certain. – Rick-777 Feb 23 '13 at 11:38