Reputation: 181
I've got this mutable list:
val array: MutableList<String> = mutableListOf("laptop on floor", "man is thomas")
How do I remove the element that contains flo
? In my case, I want to have the element laptop on floor
removed.
Upvotes: 1
Views: 629
Reputation: 9944
There are two ways to do this, depending on whether you want to change the list you already have, or create a new list.
filterNot
The more 'Kotlin' way to do this is to treat the original list as immutable, and create a copy with your changes. Treating collections as immutable helps avoid bugs and make the program easier to follow.
val list = listOf("laptop on floor", "man is thomas")
val newList = list.filterNot { "flo" in it }
After this operation, the original list
still contains both items. The
newList
copy only contains "man is thomas"
.
removeAll
If you need to modify the existing list, you can use removeAll
to remove the elements you don't want.
val list = mutableListOf("laptop on floor", "man is thomas")
list.removeAll { "flo" in it }
After this operation, you still have just the one list, and it only contains "man is thomas"
.
Upvotes: 3
Reputation: 1002
You can use:
array.removeAll { item -> item.contains("flo") }
Upvotes: 0