How to combine two object lists by id and select non-null values in kotlin… here is a solution to the problem.
How to combine two object lists by id and select non-null values in kotlin
I want to merge two object lists. Each object has a specific ID. If the same object exists in both lists, I want to merge them. If a value is null, I want to get a non-null value. For example:
val list1 = listOf(
Object(id = 1, hello, 100),
Object(id = 2, null, 40)
)
val list2 = listOf(
Object(id = 1, null, 100),
Object(id = 2, test, 40),
Object(id = 3, hi, 13)
)
The result I want to achieve is as follows:
val result = listOf(
Object(id = 1, hello, 100),
Object(id = 2, test, 40),
Object(id = 3, hi, 13)
)
Note: If a value is not empty, I know it’s no different.
Solution
fun main() {
val list1 = listOf(
Obj(id = 1, "hello", 100),
Obj(id = 2, null, 40)
)
val list2 = listOf(
Obj(id = 1, null, 100),
Obj(id = 2, "test", 40),
Obj(id = 3, "hi", 13)
)
val result = (list1.asSequence() + list2)
.groupingBy { it.id }
.reduce { _, accumulator: Obj, element: Obj ->
accumulator.copy(second = accumulator.second ?: element.second)
}
.values.toList()
println(result)
}
data class Obj(val id: Int, val second: String?, val third: Int)