在迭代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
的上下文。 你可以自己使用filter
function。
如果您正在使用列表,则不需要访问列表所在的索引。
另外,如果你已经不是,我强烈推荐使用数据类。 你的代码看起来像这样
数据类
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") } }
- 如何在values / ids.xml中获得自定义ID的引用
- Kotlingenericstypes,types推断失败
- Kotlin + Dagger2:不能提供没有@Inject构造函数或从@提供或@产生注释的方法
- 类未find,androidTest中使用Android Studio 3.0.1,Room,Kotlin的空测试套件
- 在kotlin中写入可分配的值
- Kotlin库’rxkotlin-0.21.0.jar’具有不受支持的格式。 请更新库或插件
- 在使用Kotlin协同程序时,与Room dao类错误
- 从活动Kotlin获得额外的字符串
- 在Android Java / Kotlin中,是否实现了一个接口直接访问嵌套类的本地variables