4

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.

4

2 回答 2

7

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)
}
于 2013-07-20T17:50:55.310 回答
6

如果您需要访问两个集合中相同索引处的每个元素,则可以zip使用两个集合:

for((e1, e2) <- collection1 zip collection2) {
  //Do something with e1 and e2
  //e1 is from collection1 and e2 is from collection2
}
于 2013-07-20T17:59:46.153 回答