scala 删除(就地)ListBuffer 中满足条件的所有元素
我有一个列表缓冲区。我想删除所有满足特定条件的元素。
我可以迭代它并删除每个元素。但是 Scala 对于改变你正在迭代的列表是怎么说的呢?它会起作用,还是会删除错误的元素/不返回所有元素? (对 REPL 的快速尝试表明,是的,它会搞砸)
我可以重复调用 find,然后删除找到的元素,直到找不到更多元素,但这听起来效率很低。
.filter 将返回一个没有元素的新 ListBuffer,但我想就地执行它。
这
def --= (xs: TraversableOnce[A]) : ListBuffer.this.type
Removes all elements produced by an iterator from this list buffer.
看起来很有希望,但我不太明白如何在这里使用它
我应该怎么做?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将两者结合起来并执行以下操作:
You could combine the two and do the following:
不幸的是,你无法有效地做到这一点。
--=(xs: TraversableOnce[A])
的实现(以扩展形式;实际代码更紧凑)与一次执行一个操作一样低效(即 < code>O(n*m),其中
n
是原始列表的长度,m
是要删除的项目数。一般来说,可变集合没有不可变集合那样完整和强大的一组方法。 (也就是说,它们拥有用于不可变集合的所有精彩方法,但它们自己的方法相对较少。)
因此,除非您要删除非常几个对象,否则最好将列表过滤为创建一个新的。
You can't do this efficiently, unfortunately. The implementation of
--=(xs: TraversableOnce[A])
is (in expanded form; the actual code is more compact)which is just as inefficient as doing it one at a time (i.e. it's
O(n*m)
wheren
is the length of the original list andm
is the number of items to remove).In general, the mutable collections don't have as full and powerful a set of methods as the immutable ones. (That is, they have all the wonderful methods used on immutable collections, but relatively few of their own.)
So unless you're removing very few objects, you're probably better off filtering the list to create a new one.