Bandy
Bandy

Reputation: 181

Delete item from list that contains specific substring?

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

Answers (2)

Sam
Sam

Reputation: 9944

Use removeAll to modify the existing list, or filterNot to create a copy

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

Tal Mantelmakher
Tal Mantelmakher

Reputation: 1002

You can use:

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

Upvotes: 0

Related Questions