在迭代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) } } } 

要么

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

我得到的例外

 java.lang.IllegalStateException 

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

但是使用Iterator会很笨拙,在绝大多数情况下,最好把这些集合当作Kotlin鼓励的不可变的对象。 您可以使用filter来创建一个新的集合,如下所示:

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

miensol的答案似乎是完美的。

但是,我不明白使用withIndex函数或filteredIndex的上下文。 你可以自己使用filterfunction。

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

另外,如果你已经不是,我强烈推荐使用数据类。 你的代码看起来像这样

数据类

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

过滤逻辑

 fun main(args:Array){ val eventList : MutableList = mutableListOf( Event(eventCode = "123",header = "One"), Event(eventCode = "456",header = "Two"), Event(eventCode = "789",header = "Three") ) val filteredList = eventList.filter { !it.header.equals("Two") } }