Home > Software engineering >  Merging 3 immutable maps in scala
Merging 3 immutable maps in scala

Time:02-05

I have 3 immutable maps

as: Map[UUID, A]
bs: Map[UUID, B]
cs: Map[UUID, C]

and I want to merge them so the result is of type:

Map[UUID, (Option[A], Option[B], Option[C])]

What is the best way to do this. And by best I mean fewest lines of code.

CodePudding user response:

I think you need to iterate all keys and construct the value for each of them. Something like this:

val keys = as.keySet    bs.keySet    cs.keySet
val merged = keys.map(key => (key, (as.get(key), bs.get(key), cs.get(key)))).toMap

CodePudding user response:

Probably you could use for comprehension:

for {
  k <- as.keySet    bs.keySet    cs.keySet
} yield (as.get(k), bs.get(k), cs.get(k))

CodePudding user response:

Ideally, you want a better data type that knows that at least one of the elements has to be defined. And since you mentioned cats you may do this:

import cats.syntax.all._

val result = ((as align bs) align cs)

That gives you a Map[UUID, Ior[Ior[A, B], C]] which properly represents that the result can either be a single element, a pair, or the three.

  •  Tags:  
  • Related