在迭代kotlin时从列表中删除数据

Anu*_*ody 11 android kotlin

我是kotlin编程的新手.我想要的是我想在迭代它时从列表中删除特定数据,但是当我这样做时,我的应用程序崩溃了.

for ((pos, i) in listTotal!!.withIndex()) {

            if (pos != 0 && pos != listTotal!!.size - 1) {

                if (paymentsAndTagsModel.tagName == i.header) {
                    //listTotal!!.removeAt(pos)
                    listTotal!!.remove(i)
                }



            }
        }
Run Code Online (Sandbox Code Playgroud)

要么

 for ((pos,i) in listTotal!!.listIterator().withIndex()){
            if (i.header == paymentsAndTagsModel.tagName){
                listTotal!!.listIterator(pos).remove()
            }

        }
Run Code Online (Sandbox Code Playgroud)

我得到的例外

java.lang.IllegalStateException
Run Code Online (Sandbox Code Playgroud)

mur*_*glu 20

val numbers = mutableListOf(1,2,3,4,5,6)
val numberIterator = numbers.iterator()
while (numberIterator.hasNext()) {
    val integer = numberIterator.next()
    if (integer < 3) {
        numberIterator.remove()
    }
}
Run Code Online (Sandbox Code Playgroud)


Sat*_*j S 15

miensol的答案似乎很完美.

但是,我不理解使用该withIndex函数的上下文filteredIndex.您可以单独使用该filter功能.

如果您正在使用列表,则无需访问列表所在的索引.

另外,如果您不是,我强烈建议您使用数据类.你的代码看起来像这样

数据类

data class Event(
        var eventCode : String,
        var header : String
)
Run Code Online (Sandbox Code Playgroud)

过滤逻辑

fun main(args:Array<String>){

    val eventList : MutableList<Event> = mutableListOf(
            Event(eventCode = "123",header = "One"),
            Event(eventCode = "456",header = "Two"),
            Event(eventCode = "789",header = "Three")
    )


    val filteredList = eventList.filter { !it.header.equals("Two") }

}
Run Code Online (Sandbox Code Playgroud)


mie*_*sol 10

禁止在迭代时通过其界面修改集合.改变集合内容的唯一方法是使用Iterator.remove.

然而,使用Iterators可能很笨重,在绝大多数情况下,最好将集合视为Kotlin所鼓励的不可变形.您可以使用a filter来创建一个新的集合,如下所示:

listTotal = listTotal.filterIndexed { ix, element ->
    ix != 0 && ix != listTotal.lastIndex && element.header == paymentsAndTagsModel.tagName
}
Run Code Online (Sandbox Code Playgroud)


Mus*_*ven 8

使用removeAll

pushList?.removeAll {  TimeUnit.MILLISECONDS.toMinutes(
      System.currentTimeMillis() - it.date) > THRESHOLD }
Run Code Online (Sandbox Code Playgroud)


小智 8

以下代码对我有用:

val iterator = listTotal.iterator()
for(i in iterator){
    if(i.haer== paymentsAndTagsModel.tagName){
        iterator.remove()
    }
}
Run Code Online (Sandbox Code Playgroud)

您也可以阅读这篇文章。