在 Java 中,我可以使用以下代码从列表中删除项目:
private void filterList(List<Item> items) {
Iterator<Item> iterator = items.iterator();
while (iterator.hasNext()) {
if (checkItem(iterator.next())) {
iterator.remove();
}
}
}
如何在 Kotlin 中进行相同的操作(即删除List
无需重新创建)?
只需使用.retainAll { ... } https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/retain-all.html or .removeAll { ... } https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/remove-all.html,都接受谓词,以就地过滤它:
items.retainAll { shouldRetain(it) }
items.removeAll { shouldRemove(it) }
注意items
应该是一个MutableList<T>
为此,不仅仅是List<T>
,这是 Kotlin 中的只读列表,因此不会公开任何变异函数(请参阅:收藏 https://kotlinlang.org/docs/reference/collections.html#collections在语言参考中)。
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.
如果您不想修改原始列表,您可以使用以下命令生成一个单独的集合,其中仅包含您想要保留的项目.filter { ... } https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/filter.html or .filterNot { ... } https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/filter-not.html,这适用于只读List<T>
还有:
val filtered = items.filter { shouldRetain(it) }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)