我们如何从Kotlin的MutableList中移除元素

我有以下代码,我需要在视图中显示列表的元素,然后从列表中删除这些项目。 我一直在考虑在kotlin过滤器vs地图,但没有运气找到一个解决方案。

var mutableList: MutableList<Object> = myImmutableList.toMutableList() for (x in mutableList.indices) { val tile = row!!.getChildAt(x % 4) val label = tile.findViewById(android.R.id.text1) as TextView label.text = mutableList[x].name val icon = tile.findViewById(android.R.id.icon) as ImageView picasso.load(mutableList[x].icon).into(icon) } 

由于您正在遍历整个列表,最简单的方法是在处理所有项目后调用MutableList clear方法 。

 mutableList.clear() 

其他选项可以是删除给定元素的方法删除或在给定索引删除元素removeAt 。 两者都是MutableList类的方法。 在实践中,它会看起来像这样。

 val list = listOf("a", "b", "c") val mutableList = list.toMutableList() for (i in list.indices) { println(i) println(list[i]) mutableList.removeAt(0) } 

是否有一个原因,你不能只映射和过滤最初的不可变的集合? 当你调用“List#toMutableList()”时,你已经做了一个副本,所以我不太清楚你想通过避免它来完成什么。

 val unprocessedItems = myImmutableList.asSequence().mapIndexed { index, item -> // If this item's position is a multiple of four, we can process it // The let extension method allows us to run a block and return a value // We can use this and null-safe access + the elvis operator to map our values row?.getChildAt(index % 4)?.let { val label = it.findViewById(android.R.id.text1) as TextView label.text = item.name val icon = it.findViewById(android.R.id.icon) as ImageView picasso.load(item.icon).into(icon) // Since it's processed, let's remove it from the list null } ?: item // If we weren't able to process it, leave it in the list }.filterNotNull().toList() 

再一次,不太清楚你要做什么。 我想可能有更好的方法给予更多的细节。