【问题标题】:How do we remove elements from a MutableList in Kotlin我们如何从 Kotlin 中的 MutableList 中删除元素
【发布时间】:2017-01-21 18:15:01
【问题描述】:

我有以下代码,我需要在视图中显示列表的元素,然后从列表中删除这些项目。我一直在研究 kotlin 中的过滤器与映射,但没有找到解决方案。

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

【问题讨论】:

    标签: android list kotlin


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您是否有理由不能只映射和过滤初始不可变集合?当您调用“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()
      

      再一次,不太确定你要这样做。我认为如果提供更多细节,可能会有更好的方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-12
        • 1970-01-01
        • 1970-01-01
        • 2020-04-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多