scala 删除(就地)ListBuffer 中满足条件的所有元素

发布于 2024-10-07 07:42:51 字数 443 浏览 0 评论 0原文

我有一个列表缓冲区。我想删除所有满足特定条件的元素。

我可以迭代它并删除每个元素。但是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

手心的海 2024-10-14 07:42:51

您可以将两者结合起来并执行以下操作:

val lb = ListBuffer(1,2,3,4,5,6)
lb --= lb.filter(_ % 2 == 0)

println(lb)
// outputs: ListBuffer(1, 3, 5)

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)
漆黑的白昼 2024-10-14 07:42:51

不幸的是,你无法有效地做到这一点。 --=(xs: TraversableOnce[A]) 的实现(以扩展形式;实际代码更紧凑)

xs foreach (x => this -= x) ; this

与一次执行一个操作一样低效(即 < 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)

xs foreach (x => this -= x) ; this

which is just as inefficient as doing it one at a time (i.e. it's O(n*m) where n is the length of the original list and m 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文