Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala Remove (in place) all elements of a ListBuffer that meet a condition

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?

like image 371
The Archetypal Paul Avatar asked Dec 11 '10 17:12

The Archetypal Paul


People also ask

What is Scala buffer list?

Companion object ListBufferA Buffer implementation backed by a list. It provides constant time prepend and append. Most other operations are linear.

How do I remove a set in Scala?

For deleting elements of a mutable set, we will use -= ,--=, retain, clear, remove. Deletes single element from set. Deletes multiple element from set.

How do you find the difference between two arrays in Scala?

In Scala Stack class , the diff() method is used to find the difference between the two stacks.


1 Answers

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)
like image 87
denis phillips Avatar answered Sep 20 '22 16:09

denis phillips