首页 > 解决方案 > 从 kotlin 中另一个列表中的对象更新列表中的对象

问题描述

有没有更好的方法来编写以下内容:

private fun updateImportantProperty(
    firstList: List<MyObjectX>?,
    secondList: List<MyObjectX>?
) {
    firstList?.forEach { item1 ->
        secondList?.forEach { item2 ->
            if (relatesInSomeWayToEachOther(item1, item2)) {
                item1.importantProperty = item2.importantProperty
            }
        }
    }
}

上述代码的结果可能是更新了 firstList 的 1 个对象或更新了 7 个对象(如果列表有 7 个共同对象)。

我只想更新 firstList 中对象的一个​​重要属性。不假设列表的任何内容,例如排序或大小,或者如果所有对象都在两个列表中。可读性是我所追求的。

标签: kotlin

解决方案


如果列表变大,为第一个列表的每个项目迭代整个第二个列表会变得很慢,因为这需要O(n^2)时间。

relatesInSomeWayToEachOther如果匹配项很少(即第一个列表中的每个项不会有很多匹配项,只有少数项),您可能希望通过从所有项中提取真正有意义的内容来构建某种索引第二个列表的项目,然后对第一个列表的每个项目进行快速查找。

例如:

val secondListIndex = secondList.groupBy { getIndexKey(it) }

firstList.forEach { item1 ->
    val matchingSecondListItems = secondListLookup[getLookupKey(item1)].orEmpty()
    matchingSecondListItems.forEach { item2 ->
        item1.importantProperty = item2.importantProperty
    }
}

我在这里使用了两个函数getIndexKeygetLookupKey,但是如果匹配条件很简单,这可能是同一个函数。


推荐阅读