如何使用Kotlin就地过滤列表? [英] How to filter a list in-place with Kotlin?
问题描述
在Java中,我可以使用以下代码从列表中删除项目:
In Java I can remove items from a list with this code:
private void filterList(List<Item> items) {
Iterator<Item> iterator = items.iterator();
while (iterator.hasNext()) {
if (checkItem(iterator.next())) {
iterator.remove();
}
}
}
如何在Kotlin中做到这一点(即在不重新创建的情况下删除List
中的某些项目)?
How to make the same in Kotlin (i.e. remove some items in a List
without re-creation)?
推荐答案
只需使用 .retainAll { ... }
或 .removeAll { ... }
都接受一个谓词,以对其进行就地过滤:
Just use .retainAll { ... }
or .removeAll { ... }
, both accepting a predicate, to filter it in-place:
items.retainAll { shouldRetain(it) }
items.removeAll { shouldRemove(it) }
请注意,为此,items
应该是一个MutableList<T>
,而不仅仅是List<T>
,它是Kotlin中的只读列表,因此不会公开任何变异函数(请参阅:
Note that items
should be a MutableList<T>
for that, not just List<T>
, which is a read-only list in Kotlin and thus does not expose any mutating functions (see: Collections in the language reference).
顺便说一句,对于支持随机访问的列表,有效地实现了这两个功能:然后,在删除每个项目之后,列表不会被压缩( O(n 2 )) 时间最坏的情况下),而是在处理列表时将其移至列表中,从而给 O(n)时间.
By the way, these two function are implemented efficiently for lists that support random access: then the list is not compacted after each item is removed (O(n2) time worst-case), and instead the items are moved within the list as it is processed, giving O(n) time.
如果您不想修改原始列表,则可以使用 .filterNot { ... }
,这也适用于只读List<T>
:
And if you don't want to modify the original list, you can produce a separate collection with only the items you want to retain using .filter { ... }
or .filterNot { ... }
, this will work for read-only List<T>
as well:
val filtered = items.filter { shouldRetain(it) }
val filtered = items.filterNot { shouldRemove(it) }
这篇关于如何使用Kotlin就地过滤列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!