Skip to content

Instantly share code, notes, and snippets.

@jkyamog
Created June 4, 2012 20:32
Show Gist options
  • Save jkyamog/2870693 to your computer and use it in GitHub Desktop.
Save jkyamog/2870693 to your computer and use it in GitHub Desktop.
left outer join
package experiments
object LeftOuterJoinMap {
def main(args: Array[String]) {
val map1 = Map(1 -> "a", 2 -> "b", 3 -> "c")
val map2 = Map(1 -> "1", 3 -> "3")
val joined = (new LeftOuterJoinMap(map1, map2)).join
println(joined)
}
}
class LeftOuterJoinMap[K, V1, V2](map1: Map[K, V1], map2: Map[K, V2]) {
type JoinValue = Tuple2[Option[V1], Option[V2]]
def join: Map[K, JoinValue] = {
map1.map {case (k1, v1) =>
map2.get(k1) match {
case v2: Some[V2] => (k1 -> (Some(v1), v2))
case None => (k1 -> (Some(v1), None))
}
}
}
}
@jkyamog
Copy link
Author

jkyamog commented Jun 5, 2012

Posted on scala-user. I got a more direct and shorter code.

map1.map {case (k, v) => (k -> (Some(v), map2.get(k)))}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment