我有以下功能:
override fun insertUpdatedItems(items: List<AutomobileEntity>) {
if (!items.isEmpty()) {
items.forEachIndexed { index, automobileEntity ->
if (automobileEntity.id == items[index].id) {
automobileCollection[index] = items[index]
notifyItemInserted(index)
}
}
}
}
我正在使用为 recyclerview 提供数据,我正在尝试插入已在 automobileCollection
中的更新/编辑项目,其大小总是返回 10
项目但是items
列表可能不同,它可以是 1
到 10
。
它应该通过 id
比较项目,但我目前使用此功能得到的是编辑的项目只是插入到 recyclerview 的适配器中,而不是被视为已经存在的项目。
相反,如果我使用 automobileCollection
进行迭代,我会得到 IndexOutOfBoundsException,因为大多数时候 items
列表小于 automobileCollection
。
最佳答案
要用另一个列表中的项目更新列表,您可以使用多种方法。
首先从直接替换开始(保留顺序,但这只是一个细节):
val sourceList = TODO()
val targetList = TODO()
targetList.replaceAll { targetItem ->
sourceList.firstOrNull { targetItem.id == it.id }
?: targetItem
}
或者删除所有项目并再次添加它们:
targetList.removeIf { targetItem ->
sourceList.any { it.id == targetItem.id }
}
targetList.addAll(sourceList)
使用 listIterator(注意!当您调用 replaceAll
时,这实际上也在幕后发生...不是以相同的方式,但相似 ;-)):
val iterator = targetList.listIterator()
while (iterator.hasNext()) {
iterator.next().apply {
sourceList.firstOrNull { id == it.id }?.also(iterator::set)
}
}
可能不太可读...对于您的 forEachIndexed
我没有真正看到任何用例。对于其他问题肯定存在,但我建议您尽可能多地尝试省略索引(以及 forEach
)。如果您没有想到更好的选择,那么 forEach
也可以,但很多时候,forEach
(甚至更是如此 forEachIndexed
)不是解决问题的最佳方法。
关于android - 在 Kotlin 中比较和替换两个列表中不同大小的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53477597/