如何在 Kotlin 中从 MutableList 中删除元素

8

我有以下代码,在视图中需要显示列表的元素,然后将这些项从列表中删除。我一直在研究 Kotlin 中的 filter 与 map,但没有找到解决方案。

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)
}
2个回答

12

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

mutableList.clear()

另一个选项是使用remove方法来删除指定的元素,或使用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)
}

1

你为什么不能直接使用map和filter对初始不可变集合进行操作?当你调用“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()

再次,我不太确定你的意图。如果有更多细节的话,可能会有更好的方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接