Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join two lists in Scala?

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"))
like image 769
GKVM Avatar asked Feb 16 '16 12:02

GKVM


People also ask

Can you join two lists?

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.

How do I append to a list in Scala?

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”.

Which of the following operator is used to merge list in Scala?

By using ::: If we using the List class frequently, we may prefer using ::: method. Example: Scala.


2 Answers

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))}
like image 122
ziggystar Avatar answered Sep 23 '22 03:09

ziggystar


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))
like image 32
Zoltán Avatar answered Sep 22 '22 03:09

Zoltán