ant2009
ant2009

Reputation: 22486

Concise way to find and remove items from a mutable list

kotlin

I have 2 mutableLists for new countries and current countries

I want to remove the countries from listOfCurrentCountry only if they exist in listOfNewCountry

For this I am using the removeIf and firstOrNull to check if the listOfCurrentCountry is in the listOfNewCountry.

    val listOfNewCountry = topsProductFilter.items
    val listOfCurrentCountry = selectedCountryItemsStateFlow.value

        listOfCurrentCountry.removeIf { currentCountry ->
            val result = listOfNewCountry.firstOrNull { country ->
                currentCountry.value == country.value
            }

            result == null
        }

Just wondering if there is a more kotlin concise way of doing this.

Upvotes: 1

Views: 474

Answers (3)

Twistleton
Twistleton

Reputation: 2935

You can create a new list - a more functional way:

val listOfCurrentCountry  = mutableListOf("Iceland", "Norway", "Sweden", "Finland", "Denmark")
val listOfNewCountry  = listOf("Iceland", "Denmark")
val resultList = listOfCurrentCountry - listOfNewCountry

println(resultList)  // [Norway, Sweden, Finland]

Upvotes: 1

cactustictacs
cactustictacs

Reputation: 19524

Sounds like you're in the market for removeAll

val animals = mutableListOf("pigeon", "dog", "mouse", "chupacabra", "cat")
val cartoonAnimals = listOf("cat", "mouse")
animals.removeAll(cartoonAnimals)
println(animals)

>> [pigeon, dog, chupacabra]

Upvotes: 2

Abu bakar
Abu bakar

Reputation: 871

You can make it more concise like this:

val listOfNewCountry = mutableListOf("america", "canada")
val listOfCurrentCountry = mutableListOf("america", "europe", "canada")

listOfCurrentCountry.removeIf { listOfNewCountry.contains(it) }

Upvotes: 1

Related Questions