Reputation: 361
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.
Upvotes: 0
Views: 50
Reputation: 28056
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
Upvotes: 2
Reputation: 22895
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.
Upvotes: 0
Reputation: 1734
Probably you could use for comprehension:
for {
k <- as.keySet ++ bs.keySet ++ cs.keySet
} yield (as.get(k), bs.get(k), cs.get(k))
Upvotes: 0