Search code examples
javakotlincollectionsoperators

Updating incoming list with existing data using operators


I've 2 lists

  1. Updated list coming from the server.
  2. A locally stored copy of the list that came from the server

The incoming server list data will replace the data in the localList however before doing that I need to merge data from localList into the incomingList because some items in the local list could have been modified.

I'm doing it the following way which looks Java like because of loops. Is there a Kotlin way of doing it?

val localList = List<Animal> ...
fun onIncomingData(incomingList : List<Animal>) {

    val mutableList = incomingList.toMutableList()
    
    mutableList.forEachIndex{ index, freshItem ->
       localList.forEach { localItem ->
          if(localItem is Cat && localItem.id == freshItem.id) {
             mutableList[index] = freshItem.copy(value1 = localItem.value1, value2 = localItem.value2)
            return@forEach
          }
       }
    }
}

Solution

  • Instead of the inner forEach loop, use:

    localList.find {it is Cat && it.id == freshItem.id}?.let {
        mutableList[index] = freshItem.copy(value1 = it.value1, value2 = it.value2)
    }
    

    Also, I assume your real code will do something with the mutable list you've created.