5

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
2
  • 1
    You know the j variable is useless right? Since it will always be equal to i
    – Bart
    Mar 8, 2014 at 7:02
  • You're right. I tried to ask a question that did not directly give me the answer to my problem but in the end I worded it in a bad way
    – nuclear
    Mar 8, 2014 at 7:32

2 Answers 2

12

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
1
  • This works for only two variables, it's not extendable to multiple variables as suggested by the title
    – RaphaëlR
    Dec 16, 2020 at 17:05
0

If you have multiple list to iterate over, just use .zipped on the tuple of the lists.

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

for ((c1, c2, c3) <- (l1, l2, l3).zipped) {
    println(s"$c1, $c2, $c3")
}

//Prints
1, 4, a
2, 5, b
3, 6, c

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.