I have a ListBuffer. I want to remove all elements that meet a certain condition.
I could iterate over it and remove each element. But what doe Scala say about mutating a list that you are iterating over? Will it work, or will it delete the wrong elements/not return all elements? (A quick attempt with the REPL suggests that yes, it will mess up)
I could repeatedly call find and then remove the found element until I don't find any more, but that sounds inefficient.
.filter will return me a new ListBuffer without the elements, but I want to do it in place.
This
def --= (xs: TraversableOnce[A]) : ListBuffer.this.type
Removes all elements produced by an iterator from this list buffer.
looks promising but I can't quite see how to use it here
How should I do this?
Companion object ListBufferA Buffer implementation backed by a list. It provides constant time prepend and append. Most other operations are linear.
For deleting elements of a mutable set, we will use -= ,--=, retain, clear, remove. Deletes single element from set. Deletes multiple element from set.
In Scala Stack class , the diff() method is used to find the difference between the two stacks.
You could combine the two and do the following:
val lb = ListBuffer(1,2,3,4,5,6)
lb --= lb.filter(_ % 2 == 0)
println(lb)
// outputs: ListBuffer(1, 3, 5)
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