You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Kotlin中将列表元素转移至另一个列表?

Kotlin中列表元素转移的简便方法

你当前的实现需要遍历列表两次(filter和removeIf各一次),可以优化为单次遍历的方式,同时要修正代码里的语法错误(判断相等应该用==而非=)。

方法一:使用Iterator单次遍历

直接通过迭代器遍历原列表,符合条件的元素添加到目标列表后,立即从原列表移除,整个过程只需要一次遍历:

val list = mutableListOf(1,2,3,4,5,6)
val oddList = mutableListOf<Int>()

val iterator = list.iterator()
while (iterator.hasNext()) {
    val element = iterator.next()
    if (element % 2 == 1) {
        oddList.add(element)
        iterator.remove()
    }
}

方法二:封装扩展函数复用

如果需要多次使用这种元素转移逻辑,可以封装成MutableList的扩展函数,提升代码复用性:

// 自定义扩展函数
fun <T> MutableList<T>.moveTo(destination: MutableList<T>, predicate: (T) -> Boolean) {
    val iterator = this.iterator()
    while (iterator.hasNext()) {
        val element = iterator.next()
        if (predicate(element)) {
            destination.add(element)
            iterator.remove()
        }
    }
}

// 使用示例
val list = mutableListOf(1,2,3,4,5,6)
val oddList = mutableListOf<Int>()
list.moveTo(oddList) { it % 2 == 1 }

补充说明

  • 迭代器的remove()方法是线程安全的修改方式,不会触发ConcurrentModificationException,而直接在普通for循环中修改列表会抛出该异常。
  • 单次遍历的实现比原方案更高效,尤其是处理元素数量较多的列表时。

内容的提问来源于stack exchange,提问作者yuta yanagisawa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 17:10:28