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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With