Using a for loop, how can I iterate through a list, with the ability to not iterate over the very last element in the list.
In my case, I would like to not iterate over the first element, and need to iterate through backwards, here is what I have:
for( thing <- things.reverse) {
//do some computation iterating over every element;
//break out of loop when first element is reached
}
You can drop the first item before you reverse it:
for(thing <- things.drop(1).reverse) {
}
For lists, drop(1)
is the same as tail
if the list is non-empty:
for(thing <- things.tail.reverse) {
}
or you could do the reverse first and use dropRight
:
for(thing <- things.reverse.dropRight(1)) {
}
You can also use init
if the list is non-empty:
for(thing <- things.reverse.init) {
}
As mentioned by Régis, for(thing <- things.tail.reverse) {}
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