Search code examples
androidkotlinmutablelist

Android Kotlin : Search for element with specific key value in mutableList


I have a mutableList of Cars (Cars is a data class). I'm searching a way to find the Car with a specific id in my mutable list. How can i achieve that in Kotlin?

Car.kt

data class Car(
    val createdAt: String = "",
    val updatedAt: String = "",
    val id: String = "",
    val number: String = ""
)

In my CarsFragment.kt:

var cars: MutableList<Car>

// extract Car with id = "89Ddzedzedze8998" ?

Solution

  • Use firstOrNull or find to get the result or null in case no car available with the given id.

    fun getCarById(carId: Int) {
       val myCar: Car? = carsList.firstOrNull { it.id == carId }
        // or
    
       val myCar: Car? = carsList.find { it.id == carId }
    }
    

    Now you can easily check if you get actual value or null, and move further accordingly.