Search code examples
scalascala-cats

Merging 3 immutable maps in scala


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.


Solution

  • 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