Scala iterate through the list except the last item

Using a for loop, how can I iterate over a list, being able to not iterate over the very last element in the list.

In my case, I would like not to iterate over the first element and iterate over backwards, this is what I have:

        for( thing <- things.reverse) {
          //do some computation iterating over every element; 
          //break out of loop when first element is reached
        }
+3
source share
2 answers

You can discard the first element before undoing it:

for(thing <- things.drop(1).reverse) {
}

For lists, the drop(1)same as tailif the list is not empty:

for(thing <- things.tail.reverse) {
}

or you can do the opposite first and use dropRight:

for(thing <- things.reverse.dropRight(1)) {
}

You can also use initif the list is not empty:

for(thing <- things.reverse.init) {
}
+10
source

As mentioned by Rigis, for(thing <- things.tail.reverse) {}

+3
source

All Articles