Vishwas
Vishwas

Reputation: 7067

How to combine two lists using 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"))

Upvotes: 4

Views: 2113

Answers (3)

mohit
mohit

Reputation: 4999

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.

Upvotes: 7

Sergii Lagutin
Sergii Lagutin

Reputation: 10661

First zip tuples in sequnces:

val lists = for {i <- 0 until A.length
     a = A(i)
     b = B(i)
} yield (a.productIterator ++ b.productIterator).toList

Next define converter from Seq back to Product:

def toTuple(seq: Seq[_]): Product = {
  val clz = Class.forName("scala.Tuple" + seq.size)
  clz.getConstructors()(0).newInstance(seq.map(_.asInstanceOf[AnyRef]): _*).asInstanceOf[Product]
}

And finally do map:

lists.map(toTuple)

This code does not consider different arity of input lists and tuple size's limitation.

Upvotes: -1

Dima
Dima

Reputation: 40500

A.zip(B).map { case ((a,b,c,d), (p,q,r,s,t)) => (a,b,c,d,p,q,r,s,t) }

Upvotes: 1

Related Questions