Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine two lists using scala?

Tags:

scala

I have following lists -

val A = List(("A","B","C","D"),("A1","B1","C1","D1"),("A2","B2","C2","D2"))

and

val B = List(("P","Q","R","S","T"),("P1","Q1","R1","S1","T1"),("P2","Q2","R2","S2","T2"),("P3","Q3","R3","S3","T3"))

I want to merge 1st element of list A with first element of list B and so on. here list A have 3 elements and B have 4. I want to consider number of elements in list A while merging.

output as below

val combineList = List(("A","B","C","D","P","Q","R","S","T"),("A1","B1","C1","D1","P1","Q1","R1","S1","T1"),
        ("A2","B2","C2","D2","P2","Q2","R2","S2","T2"))
like image 561
Vishwas Avatar asked Mar 18 '23 09:03

Vishwas


1 Answers

If you can use shapeless, then you can simply do

scala> import shapeless.syntax.std.tuple._
scala> A.zip(B).map{case(a,b) => a ++ b}
res1: List[(String, String, String, String, String, String, String, String, String)] = List((A,B,C,D,P,Q,R,S,T), (A1,B1,C1,D1,P1,Q1,R1,S1,T1), (A2,B2,C2,D2,P2,Q2,R2,S2,T2))

It will work on arbitrary size of tuples.

like image 72
mohit Avatar answered Mar 28 '23 02:03

mohit