【问题标题】:Remove item from mutable list added from a model in kotlin从 kotlin 中的模型添加的可变列表中删除项目
【发布时间】:2020-09-05 22:21:03
【问题描述】:

在我的代码中,我创建了一个可变列表并从模型中添加元素:

var lista: MutableList<ExpenseItem> =  mutableListOf()
...
class ExpenseItem (val name: String, val word: String, val flavour: String)
...
      val currentExpense = ExpenseItem("Sergio", "Aguacate", "Duro")
            val currentExpense1 = ExpenseItem("amaya", "fresas", "pan")
            val currentExpense2 = ExpenseItem("emma", "limon", "agua")

            lista.add(currentExpense)
            lista.add(currentExpense1)
            lista.add(currentExpense2)

现在我正在寻找一种删除元素的方法,例如“名称”字段

我已经尝试了列表的过滤器、删除、删除等。我也尝试过“何时”,但我认为我没有找到正确的语法或方法,

非常感谢您的帮助。

【问题讨论】:

  • 您在寻找lista.removeAll { it.name == nameToRemove }吗?
  • 是的,先生,谢谢...我刚开始使用 kotlin :D

标签: android kotlin collections


【解决方案1】:

听起来你想要的方法是

lista.removeAll { it.name == nameToRemove }

【讨论】:

    【解决方案2】:

    如果您打算修改实际列表,则需要 removeAll。

    lista.removeAll {
         it.name == "nameToRemove"
    }
    

    如果你不想修改原来的列表,那么filter可以得到一个没有这些元素的新列表。

    val newList = lista.filter{
         it.name != "nameToRemove"
    }
    

    下面显示了行为的完整解释

    var list: MutableList<String> =  mutableListOf("1","2", "3")
    
    //Shows all items
    list.forEach {
        println(it)
    }
    
    //Makes a new list with all items that are not equal to 1
    val newList = list.filter {
        it != "1"
    }
    newList.forEach {
        println(it)
    }
    
    //Original list is untouched
    list.forEach {
        println(it)
    }
    
    //Modifies this list to remove all items that are 1
    list.removeAll {
        it == "1"
    }
    list.forEach {
        println(it)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-06
      • 1970-01-01
      • 1970-01-01
      • 2018-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多