简体   繁体   中英

Comparing and replacing items in two lists with different sizes in Kotlin?

I have the following function:

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)
                }
            }
        }
    }

I'm using to provide data for a recyclerview, I'm trying to insert updated/edited items that are already in automobileCollection which size always returns 10 items but the items list might differ it can be 1 to 10 .

It's supposed to compare items by id but what I'm getting currently with this function is the edited items are just inserted to recyclerview's adapter and not treated as an already existing item.

On the contrary, if I iterate using automobileCollection I get IndexOutOfBoundsException since most of the time the items list is smaller than automobileCollection .

To update a list with items from another one, you can use several ways.

First starting with a direct replacement (which preserves the order, but that's just a detail):

val sourceList = TODO()
val targetList = TODO()

targetList.replaceAll { targetItem -> 
  sourceList.firstOrNull { targetItem.id == it.id } 
            ?: targetItem
}

Alternatively removing all the items and adding them again:

targetList.removeIf { targetItem ->
  sourceList.any { it.id == targetItem.id }
}
targetList.addAll(sourceList)

Using listIterator (note! that's actually also happening under the hood when you call replaceAll ... not in the same way, but similar ;-)):

val iterator = targetList.listIterator()
while (iterator.hasNext()) {
  iterator.next().apply {
    sourceList.firstOrNull { id == it.id }?.also(iterator::set)
  }
}

Probably not so readable... For your forEachIndexed I do not really see any use-case. For other problems there definitely are, but I would suggest you try to omit indices (and also forEach ) as often as you can. If nothing better comes to your mind, then forEach is also ok, but many times, forEach (and even more so forEachIndexed ) isn't the best approach to solve an issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM