Home > Software design >  Kotlin compare two lists - if ids match overwrite it
Kotlin compare two lists - if ids match overwrite it

Time:10-14

I have two lists of Object. Both objects have an id val. I need to check both lists by the id val, if the id is the same take the object from list B and overwrite it in list A. Is there a simple up to date way to achieve this outcome in kotlin?

Ive been searching through the kotlin docs and other comparing list questions on here but I havent found anything in the docs or on here that matches my usecase

CodePudding user response:

Not sure about how efficient this is but it works...

Sample Class

data class SomeClass(val id: Int, val someString: String) {

}

fun transformList(firstList: List<SomeClass>, secondList: List<SomeClass>): List<SomeClass> {
    return firstList.map { firstClass ->
        val tempItem = secondList.firstOrNull { it.id == firstClass.id }
        tempItem ?: firstClass
    }
}

basically, the function takes both the lists and compares each item with each other, and returns items from list 2 if the id is the same.

fun main() {

    val listOne = listOf<SomeClass>(
        SomeClass(0, "I am 0, from list 1"),
        SomeClass(1, "I am 1, from list 1"),
    )

    val listTwo = listOf<SomeClass>(
        SomeClass(0, "I am 0, from list 2"),
        SomeClass(1, "I am 1, from list 2"),
    )

    println(transformList(listOne, listTwo))

}

Output

 [SomeClass(id=0, someString=I am 0, from list 2), SomeClass(id=1, someString=I am 1, from list 2)]
  • Related