简体   繁体   中英

How do I make UpdateOrInsert in Kotlin collections

I have a list of items, and one of item copies is changed by user, how do I find it in my collection by Id and update, or if it's not found I'd like to add the item? my best guess is, but it requires ugly indexOf(v)

fun updateOrInsert(note : UserNote) {
    val list = notes.value!!
    val v = list.firstOrNull{(Id) -> Id ==note.Id}
    if (v==null) {
        list.add(note)
    } else {
        val i = list.indexOf(v)
        list[i] = note
    }

    notes.value = list
}

Use indexOfFirst to find the index of the first element with the given ID. If -1, add the item to the list, otherwise, change the value at the found index.

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