Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala for loop with multiple variables

How can I translate this loop (in Java) to Scala?

for(int i = 0, j = 0; i < 10; i++, j++) {
  //Other code
}

My end goal is to loop through two lists at the same time. I want to get both elements at the same time at each index in the iteration.

for(a <- list1, b <- list2) // doesn't work

for(a <- list1; b <- list2) // Gives me the cross product
like image 875
nuclear Avatar asked Dec 26 '22 12:12

nuclear


1 Answers

Use .zip() to make a list of tuple and iterate over it.

val a = Seq(1,2,3)
val b = Seq(4,5,6)
for ((i, j) <- a.zip(b)) {
  println(s"$i $j")
}
// It prints out:
// 1 4
// 2 5
// 3 6
like image 109
kawty Avatar answered Jan 06 '23 14:01

kawty