Last active
April 26, 2017 13:45
-
-
Save TomLous/2e6015cdd8db0f5bc2108cd86fb906e6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Merging two maps keeping the first value if avaialble, otherwise second | |
| */ | |
| val map1 = Map("a"->Some(1), "b"->Some(3), "c"->None, "d"->None, "h"->Some(34)) | |
| val map2 = Map("a"->None, "b"->Some(11), "c"->Some(22), "d"->None, "e"->Some(12), "f"->None) | |
| // Option1 | |
| (map1.toList ++ map2.toList) | |
| .groupBy(_._1) | |
| .mapValues(_.flatMap(_._2).headOption) | |
| // Option2 | |
| (map2 ++ map1).map{ | |
| case (k,None) => k->map2.get(k).flatten | |
| case z => z | |
| } | |
| // Option 3 | |
| (map1.keys ++ map2.keys).map(k => k -> (map1.get(k) ++ map2.get(k)).flatten.headOption).toMap |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment