Reputation: 335
We have two lists:
val a:List[(String, Int, Int)] = List(("apple", 3, 25),("orange", 4, 47))
val b:List[(String, String)] = List(("mango", "25"),("orange", "50"))
Which is the best method to Join a and b to get:
val c : List[(String, Int, Int, String)] = List(("orange", 4, 47, "50"))
Upvotes: 5
Views: 7383
Reputation: 28686
Iterate over the first list and lookup the values of the second list in a map mb
. The .flatMap
makes the entry dissappear, if the .get
returns None
.
val mb = b.toMap
a.flatMap{case (ka,va,vva) => mb.get(ka).map(vb => (ka,va,vva,vb))}
Upvotes: 11
Reputation: 22196
You can concatenate the lists, and then group them by the first element of your tuple:
val groupedTuples: Map[String, List[(String, String)]] = (a ++ b).groupBy(_._1)
val c: Map[String, List[String]] = groupedTuples.mapValues(_.map(_._2))
This will result in
Map(mango -> List(25), orange -> List(4, 50), apple -> List(3))
Upvotes: 2