Search code examples
androidarrayslistloopskotlin

Change a value in mutable list in Kotlin


I got this mutablelist:

[Videos(id=4, yt_id=yRPUkDjwr1A, title=test4, likes=0, kat=pranks, ilike=false), Videos(id=3, yt_id=WkyUU9ZDUto, title=test3, likes=0, kat=pranks, ilike=false), Videos(id=2, yt_id=B_X9OQqtduE, title=test2, likes=0, kat=animals, ilike=false), Videos(id=1, yt_id=ywaKlGNiv80, title=test1, likes=0, kat=animals, ilike=false)]

How can I change ilike to true where id is 2

This is what I've tried:

for (i in 0 until vids!!.size) {
    Log.d("lets", vids!!.get(i).title)
        
    if(vids!!.get(i).id == 2){
        vids!!.get(i).ilike = true
    }
}

Solution

  • You can use find function to find the element with id = 2 and change its property:

    vids?.find { it.id == 2 }?.iLike = true
    

    Note: it is a good practice to use question mark if the property is nullable and you unsure whether it is null or not.