Home > Blockchain >  What is the easiest way to change element in the list Kotlin?
What is the easiest way to change element in the list Kotlin?

Time:01-23

I got a list of objects Exercize(). So it contains Exercize(time=9,name=pushup), Exercize(time=10,name=run),Exercize(time=12,name=swim). After click I got an item for example Exercize(time=10, name=burpy) so I need to find in the list the object with the same time and change it in the list. So as a result my list will be Exercize(). So it contains Exercize(time=9,name=pushup), Exercize(time=10,name=burpy),Exercize(time=12,name=swim)

How I can make it easier in kotlin?

CodePudding user response:

Code to update item in the list by specific property:

list.find { it.id == newItem.id }?.name = newItem.name

Full code example based on your answer:

val listOfExercizes = listOf(
    Exercize(time = 9, name = "pushup"),
    Exercize(time = 10, name = "run"),
    Exercize(time = 12, name = "swim")
)
println("List before changes: $listOfExercizes")

val newExercize = Exercize(time = 10, name = "burpy")

listOfExercizes.find { it.time == newExercize.time }?.name = newExercize.name

println("List after changes: $listOfExercizes")

Having next model class:

data class Exercize(val time: Int, var name: String)

CodePudding user response:

I'm assuming Exercise is an immutable class.

You can search for the index of the item to replace with indexOfFirst. If the index returned is negative, it means nothing fit the predicate. I suppose in that case you might just want to add the new item instead of swapping it in. Or maybe you would want to throw an error.

val exercisesList = mutableListOf(
    Exercize(time=9,name="pushup"), 
    Exercize(time=10,name="run"),
    Exercize(time=12,name="swim")
)
val burpee = Exercize(time=10,name="burpee")
val foundIndex = exercisesList.indexOfFirst { it.name == burpee.name }
if (foundIndex >= 0) {
    exercisesList[foundIndex] = burpee
} else {
    exercisesList  = burpee
}

Maybe you were hoping for something shorter, but Kotlin doesn't provide many MutableList operators in the standard library. You could make this into one like this:

inline fun <T> MutableList.replaceFirstOrAdd(item: T, predicate: (T)->Boolean) {
    val index = indexOfFirst(predicate)
    if (index >= 0) {
        this[index] = item
    } else {
        add(item)
    }
}
  • Related