Jet Jet - 1 year ago 125
Scala Question

Loop the second list based on the first list

I got two lists

l1
and
l2
, based on the
l1
,
l2
need to be looped.

val l1 = List("a", "b")
val l2 = List(1, 2, 3, 4, 5, 6)


I tried like this, but not getting the right result

l1.map { x =>
l2.map { y =>
println(x, y)
}
}


Result got

(a,1)
(a,2)
(a,3)
(a,4)
(a,5)


Here
l2
is looping until the end of items in that list, but I want it to loop only once for each item in
l1
and for the second item in the
l1
,
l2
need to be looped again for once but with the next item in the list.

Result expected

(a,1)
(b,2)


Thanks in advance.

Answer Source

You can use zip to do this:

l1 zip l2