我想合并两个对象列表。每个对象都有一个特定的 ID。如果两个列表中存在相同的对象,我想合并它们。如果一个值为空,我想得到非空值。例如:
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)
)
我要实现的结果如下:
val result = listOf(
Object(id = 1, hello, 100),
Object(id = 2, test, 40),
Object(id = 3, hi, 13)
)
注意:如果一个值不为空,我知道它没有什么不同。
最佳答案
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)
关于java - 如何通过 id 组合两个对象列表并在 kotlin 中选择非空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64232688/