There are two lists:
val listA:List<Amodel>
val listB:List<Int>
data class Amodel(val id:Int,var isUsed:Boolean=false)
Need to update listA isUsed =true based on the int id of the listB
What I'm doing now:
listB.foreach(){
//here i'm updating but it's taking too much time w.r.t time efficiency.
}
any GOOD solution.
Note list size is 500k for simulation
CodePudding user response:
This might be slightly faster when the lists are huge:
val lookup = listB.associateWith { true }
listA.forEach { it.isUsed = lookup[it.id] ?: false }
Possibly this is even faster, I'm not sure. Because it then only sets isUsed
in the case it needs to be true:
val lookup = listB.associateWith { true }
listA.forEach { lookup[it.id]?.run { it.isUsed = true } }
CodePudding user response:
data class Amodel(val id: Int, var isUsed: Boolean = false)
val listA: List<Amodel> = listOf(
Amodel(1),
Amodel(2),
Amodel(3),
Amodel(4),
Amodel(5)
)
val listB: List<Int> = listOf(2, 4, 5)
listA.forEach { if (it.id in listB) it.isUsed = true }
// Alternative to set all items, not only from false to true:
listA.forEach { it.isUsed = it.id in listB }
println(listA)
Output:
[
Amodel(id=1, isUsed=false),
Amodel(id=2, isUsed=true),
Amodel(id=3, isUsed=false),
Amodel(id=4, isUsed=true),
Amodel(id=5, isUsed=true)
]