Iterate over two collections in one loop

What is an elegant way to iterate over two collections in Scala using a single loop?

I want the values ​​from the first collection to be second, for example:

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

I actually use the Iterable trait, so it’s better if you provide a solution that is applicable to Iterable .

Please note: I do not want to copy values ​​from one to another. I need to access the i'th element of the first and second collection in a loop Thanks.

+4
source share
2 answers

If you need to access each item from one index from both collections, you can zip create two collections:

 for((e1, e2) <- collection1 zip collection2) { //Do something with e1 and e2 //e1 is from collection1 and e2 is from collection2 } 
+6
source

It doesn't seem like you want to iterate over the second collection at all, but you want a pointer to what you are working on, which is suitable for zipWithIndex for:

 for ((el, i) <- collection1.zipWithIndex) { collection2.setValueAtIndex(el, i) } 
+7
source

Source: https://habr.com/ru/post/1492492/


All Articles