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

时间:2018-02-02 06:48:09

标签: 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)
                }



            }
        }

OR

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

        }

我得到的例外

java.lang.IllegalStateException

6 个答案:

答案 0 :(得分:11)

miensol的回答似乎很完美。

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

  

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

另外,如果您已经没有,我强烈建议您使用数据类。您的代码看起来像这样

数据类

data class Event(
        var eventCode : String,
        var header : String
)

过滤逻辑

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") }

}

答案 1 :(得分:9)

迭代它时禁止modify a collection through its interface。改变集合内容的唯一方法是使用Iterator.remove

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

listTotal = listTotal.filterIndexed { ix, element ->
    ix != 0 && ix != listTotal.lastIndex && element.header == paymentsAndTagsModel.tagName
}

答案 2 :(得分:7)

使用removeAll

pushList?.removeAll {  TimeUnit.MILLISECONDS.toMinutes(
      System.currentTimeMillis() - it.date) > THRESHOLD }

答案 3 :(得分:3)

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()
    }
}

答案 4 :(得分:0)

使用while循环,这是kotlin扩展功能:

Dim userInput As Integer
If Integer.TryParse(PickUpInputTextBox.Text, userInput) Then
    If (userInput > 0) Then
        ' ... other existing code ...
    Else
        MessageBox.Show("You must pick up one or more sticks!")
    End If
Else
    MessageBox.Show("Inavlid Number of Sticks to Pick Up!")
End If

答案 5 :(得分:0)

以下代码对我有用:

val iterator = listTotal.iterator()
for(i in iterator){
    if(i.haer== paymentsAndTagsModel.tagName){
        iterator.remove()
    }
}

您也可以阅读this文章。