Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate two collections in one loop

Tags:

scala

What is the elegant way to iterate two collections in Scala using one loop?

I want set values from first collection to second, like this:

// pseudo-code
for (i <- 1 to 10) {
  val value = collection1.get(i);
  collection2.setValueAtIndex(value, i) ;
}

In fact I use Iterable trait, so its better if you provide solution applicable for Iterable.

Please note: I don't want to copy values from one to another. I need to access in loop to i'th element of first and second collection Thanks.

like image 617
WelcomeTo Avatar asked Dec 12 '22 13:12

WelcomeTo


1 Answers

It doesn't look like you want to iterate the second collection at all, but want the index of the thing you're working on, which is what zipWithIndex is good for:

for ((el, i) <- collection1.zipWithIndex) {
  collection2.setValueAtIndex(el, i)
}
like image 76
Derek Wyatt Avatar answered Jan 03 '23 15:01

Derek Wyatt