nuclear
nuclear

Reputation: 365

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

Upvotes: 5

Views: 5323

Answers (2)

Rapha&#235;lR
Rapha&#235;lR

Reputation: 542

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

Upvotes: 0

kawty
kawty

Reputation: 1656

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

Upvotes: 12

Related Questions