Kotlin list在遍历时删除元素方法汇总

Kotlin list在遍历时删除元素方法汇总,第1张

方法一:Iterator迭代器
val list = arrayListOf("1", "2", "3", "4", "5", "6")

val iterator = list.iterator()
while (iterator.hasNext()){
    if (iterator.next() == "4"){
        iterator.remove()
    }
}
        
println("result: $list")  //result: [1, 2, 3, 5, 6]
方法二:for循环
val list = arrayListOf("1", "2", "3", "4", "5", "6")

for (index in list.size - 1 downTo 0){
    if (list[index] == "3") {
        list.removeAt(index)
    }
}

println("result: $list") //result: [1, 2, 4, 5, 6]
方法三:removeIf
val list = arrayListOf("1", "2", "3", "4", "5", "6")

//minSdkVersion >= 24(N)
list.removeIf {
    it == "5"
}

println("result: $list") //result: [1, 2, 3, 4, 6]
方法四:removeAll + filter
val list = arrayListOf("1", "2", "3", "4", "5", "6")

list.removeAll(list.filter {
    it == "2"
})

println("result: $list") //result: [1, 3, 4, 5, 6]

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/905008.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-15
下一篇 2022-05-15

发表评论

登录后才能评论

评论列表(0条)

保存