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.
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)
}
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