从列表中删除包含特定子字符串的项目?

时间:2020-08-29 12:26:55

标签: kotlin

我有这个可变的列表:

val array: MutableList<String> = mutableListOf("laptop on floor", "man is thomas")

如何删除包含flo的元素?就我而言,我想删除元素laptop on floor

2 个答案:

答案 0 :(得分:2)

使用removeAll修改现有列表,或使用filterNot创建副本

有两种方法可以执行此操作,具体取决于您是要更改现有列表还是创建新列表。

filterNot

执行此操作的更多“科特林”方法是将原始列表视为不可变的,并使用您的更改创建一个副本。将集合视为不可变的集合有助于避免错误,并使程序易于遵循。

val list = listOf("laptop on floor", "man is thomas")
val newList = list.filterNot { "flo" in it }

执行此操作后,原始list仍包含两个项目。的 newList副本仅包含"man is thomas"

removeAll

如果需要修改现有列表,可以使用removeAll删除不需要的元素。

val list = mutableListOf("laptop on floor", "man is thomas")
list.removeAll { "flo" in it }

完成此操作后,您仍然只有一个列表,并且仅包含"man is thomas"

答案 1 :(得分:0)

您可以使用:

array.removeAll { item -> item.contains("flo") }