如何通过id合并两个对象列表并选择非空值在Kotlin中

huangapple go评论81阅读模式
英文:

How to combine two object lists by id and select non-null values in kotlin

问题

我想要合并两个对象列表。每个对象都有一个特定的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)
)

**注意:如果一个值不为空,我知道它是相同的。**
英文:

I want to combine two object lists. Each object has a specific id. If the same object exists in two lists, I want to merge them. And if a value is null I want to get the non-null one. 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 is not different.

答案1

得分: 3

fun main() {
    val list1 = listOf(
        Obj(id = 1, "你好", 100),
        Obj(id = 2, null, 40)
    )

    val list2 = listOf(
        Obj(id = 1, null, 100),
        Obj(id = 2, "测试", 40),
        Obj(id = 3, "嗨", 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)
英文:
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)

答案2

得分: 0

有两种方法可以解决这个问题,一种是O(n^2)的方法,其中你要遍历两个列表并检查每个对象。另一种是O(n)的方法,其中你会浪费一些额外的空间,通过在一个字典中创建映射,然后在一个列表上进行循环,同时在另一个列表上进行检查。

英文:

There can be 2 approaches to the problem, O(n^2) approach where you loop through both the lists and check for each object. Or O(n) approach where you waste some extra space by creating a mapping in one dictionary for your list and looping on one while checking in other.

huangapple
  • 本文由 发表于 2020年10月7日 03:36:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/64232688.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定