scala 移除(就地)ListBuffer 中满足条件的所有元素 [英] scala Remove (in place) all elements of a ListBuffer that meet a condition

查看:64
本文介绍了scala 移除(就地)ListBuffer 中满足条件的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ListBuffer.我想删除所有满足特定条件的元素.

I have a ListBuffer. I want to remove all elements that meet a certain condition.

我可以遍历它并删除每个元素.但是 Scala 对改变你正在迭代的列表有什么看法呢?它会起作用,还是会删除错误的元素/不返回所有元素?(使用 REPL 的快速尝试表明是的,它会搞砸)

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)

我可以反复调用 find 然后删除找到的元素,直到找不到更多元素为止,但这听起来效率很低.

I could repeatedly call find and then remove the found element until I don't find any more, but that sounds inefficient.

.filter 将返回一个没有元素的新 ListBuffer,但我想就地做.

.filter will return me a new ListBuffer without the elements, but I want to do it in place.

这个

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

我该怎么做?

推荐答案

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

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

这和一次做一个一样低效(即它是 O(n*m),其中 n 是原始列表的长度,m 是要删除的项目数).

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.

这篇关于scala 移除(就地)ListBuffer 中满足条件的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆