Easing into cats from Geekabyte For full story you can check it out on the blog.
Merging two maps
Given two maps of type Map[Sting, List[String]], combine them to create a resulting map where identical keys from the three maps have their list values concatenated in the combined map.
So for example, combining
Map("k1" -> List("One"), "k2" -> List("Zero")) and Map("k1" -> List("Two")) should give Map("k1" -> List("One", "Two"), "k2" -> List("Zero")).
Use the following test data for implementation:
val movies1 = Map(
"Will Smith" -> List("Wild Wild West", "Bad Boys", "Hitch"),
"Jada Pinkett" -> List("Woo", "Ali", "Gotham")
)
val movies2 = Map (
"Will Smith" -> List("Made in America"),
"Angelina Jolie" -> List("Foxfire", "The Bone Collector", "Original
Fiddle Around!
val movies1 = Map(
"Will Smith" -> List("Wild Wild West", "Bad Boys", "Hitch"),
"Jada Pinkett" -> List("Woo", "Ali", "Gotham")
)
val movies2 = Map (
"Will Smith" -> List("Made in America"),
"Angelina Jolie" -> List("Foxfire", "The Bone Collector", "Original Sin")
)
// Have your solution here that would produce
// Map(Will Smith -> List(Wild Wild West, Bad Boys, Hitch, Made in America), Angelina Jolie -> List(Foxfire, The Bone Collector, Original Sin), Jada Pinkett -> List(Woo, Ali, Gotham))
Scala Solution
val movies1 = Map(
"Will Smith" -> List("Wild Wild West", "Bad Boys", "Hitch"),
"Jada Pinkett" -> List("Woo", "Ali", "Gotham")
)
val movies2 = Map (
"Will Smith" -> List("Made in America"),
"Angelina Jolie" -> List("Foxfire", "The Bone Collector", "Original Sin")
)
val dZero = Map[String, List[String]]().withDefaultValue(List[String]())
val res = (movies1.toList ++ movies2.toList).foldLeft(dZero) {
case (m, (k, v)) => m.updated(k, m(k) ++ v)
}
println(res)
Cats Solution
import cats._
import cats.data._
import cats.implicits._
val movies1 = Map(
"Will Smith" -> List("Wild Wild West", "Bad Boys", "Hitch"),
"Jada Pinkett" -> List("Woo", "Ali", "Gotham")
)
val movies2 = Map (
"Will Smith" -> List("Made in America"),
"Angelina Jolie" -> List("Foxfire", "The Bone Collector", "Original Sin")
)
val merged = movies1 |+| movies2