android - 在 Kotlin 中比较和替换两个列表中不同大小的项目?

标签 android list collections kotlin

我有以下功能:

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 列表可能不同,它可以是 110

它应该通过 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/

相关文章:

java - 我是否可以有一个可以同时采用 HashMap 或列表作为参数的方法?

java - 将 ListIterator 限制为前 N 个元素(优化)

java - 什么决定比较器/可比较集合类中的升序或降序?

android - 防止多行 TextView 不必要地扩展到它的最大宽度

android - 未定义不是 React Native 项目中的函数

Python list.index() 与字典

java - 如何随机播放 ArrayList 的特定范围?

android - 如何禁用 Achartengine 上的缩放图标

java - 同步关键词

list - Cython - 使用 python 列表初始化向量 [int]