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"))
We can use + operator to merge two lists i.e. It returned a new concatenated lists, which contains the contents of both list_1 and list_2.
This is the first method we use to append Scala List using the operator “:+”. The syntax we use in this method is; first to declare the list name and then use the ':+' method rather than the new element that will be appended in the list. The syntax looks like “List name:+ new elements”.
By using ::: If we using the List class frequently, we may prefer using ::: method. Example: Scala.
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))}
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With