3

I have two ArrayList(List[String]) e.g:

ArrayList1:           ArrayList1:
List(a, b, c)         List(1, 2, 3)
List(d, e, f)         List(4, 5, 6)
List(g,h, i)          List(7,8, 9)

I want to use scala to join in parallel such as doing this

val ArrayList12 = ArrayList1 ++ ArrayList2 

but this is not what I want since the ArrayList2 got added at the end of ArrayList1

Please I will appreciate help using scala to have a parallel join in this form:

List(a, b, c,1,2,3) 
List(d, e, f,4,5,6)
List(g,h,i,7,8,9)

3 Answers 3

2

You can use zip.

val arrayList12 = arrayList1.zip(arrayList2).map(tuple => tuple._1 ++ tuple._2)

zip returns a List that combines each element of the first and the second list into a Tuple2, the resulting type is Seq[(List[A],List[Int])]. Then we can map that list to to a flat structure with map to concatenate the two lists in the Tuple.

Sign up to request clarification or add additional context in comments.

10 Comments

Surely .map(x => x._1 ++ x._2) ?
@BrianAgnew Same thing, Scala allows this shorter syntax aswell :) See here: stackoverflow.com/questions/7673545/…
But isn't the _ positional - that is, using it twice suggests two different args, whereas in fact you want the one argument (the tuple) with the two fields ?
Did you try the flatten one? Hint: it doesn't work, there's no flatten for tuples. And the first doesn't compile either (extra . before the digit)
@TaiwoO.Adetiloye - Good to know. I've just undeleted my answer following your comment
|
1

Try this:

scala>  List(List("a","b","c"), List("d", "e", "f"))
res1: List[List[String]] = List(List(a, b, c), List(d, e, f))

scala>  List(List(1,2,3),List(4,5,6))
res2: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6))

scala> res1.zip(res2)
res3: List[(List[String], List[Int])] = List((List(a, b, c),List(1, 2, 3)), (List(d, e, f),List(4, 5, 6)))

which gives a List of tuples. You can then map() across these, adding the two elements of each tuple:

scala> res1.zip(res2).map(x => x._1 ++ x._2)
res5: List[List[Any]] = List(List(a, b, c, 1, 2, 3), List(d, e, f, 4, 5, 6))

3 Comments

I don't think I did. I tried yours in the REPL with no joy, due to the positional placeholders
@TheArchetypalPaul - just done that following comments
Sorry for the confusion! Honest mistake!
0

Just another way of skinning the cat:

val arrayList1 = List(List("a","b","c"), List("d", "e", "f"), List("g","h", "i"))
val arrayList2 =List(List("1","2","3"), List("4", "5", "6"), List("7", "8", "9"))
List(arrayList1, arrayList2).transpose.map(_.flatten)
// List(List(a, b, c, 1, 2, 3), List(d, e, f, 4, 5, 6), List(g, h, i, 7, 8, 9))

But if I were doing it for real, I'd use Brian Agnew's answer

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.