Home > database >  Concise way to find and remove items from a mutable list
Concise way to find and remove items from a mutable list

Time:06-02

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.

CodePudding user response:

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]

CodePudding user response:

You can make it more concise like this:

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

listOfCurrentCountry.removeIf { listOfNewCountry.contains(it) }
  • Related