https://kotlinlang.org logo
#codereview
Title
# codereview
i

iamthevoid

08/09/2022, 6:46 AM
What is the best way to replace multiple elements in list from another list? For example - some entities from list updates from server and should be replaced in cache by id In general in the case we have two lists of unknown size, let say N And loop gets us that calculation time will be O(n^2) - whether we should loop incoming list and then replace in stored with foreach or conversely Now i solve this like that , but something tell me that speed and performance could be better
Copy code
fun replaceAlerts(newAlerts: List<ExternalAlert>) {
        val data = stateFlow.value
        val existsAlerts = data.alerts.toMutableList()
        newAlerts.forEach { newAlert ->
            for (i in existsAlerts.indices) {
                if (newAlert.id == existsAlerts[i].id) {
                    existsAlerts[i] = newAlert
                    return@forEach
                }
            }
            existsAlerts.add(newAlert)
        }
        stateFlow.value = data.copy(alerts = existsAlerts)
    }
Maybe i should use DiffUtils from android, and looks like it is the best option, but how to implement it in jvm-only module? 😞
j

Joffrey

08/09/2022, 7:25 AM
If you used a map to store the current state, you could update each entity in constant time, leading to linear time overall to update from a list
i

iamthevoid

08/09/2022, 7:28 AM
Update takes constant time, you're correct, but on each map callback call i should loop incoming list to find item, that should replace exists item, so i get N*N - first N - loop original list and second N to loop incoming list to find correct item
j

Joffrey

08/09/2022, 7:31 AM
I think you misunderstood me. I'm talking about using a
Map
data structure instead of a list for the current items. If you do this, you only need to iterate the list of incoming items to update, and you can find the corresponding item by id in the map in constant time
i

iamthevoid

08/09/2022, 7:42 AM
Good solution, thanks!
61 Views