kotlin - 从 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 中对象的一个重要属性。不假设列表的任何内容,例如排序或大小,或者如果所有对象都在两个列表中。可读性是我所追求的。
解决方案
如果列表变大,为第一个列表的每个项目迭代整个第二个列表会变得很慢,因为这需要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
}
}
我在这里使用了两个函数getIndexKey
和getLookupKey
,但是如果匹配条件很简单,这可能是同一个函数。
推荐阅读
- java - 为什么我的 Spring Boot 应用程序出现异常?
- python - 如何将日期时间从 tkcalendar 转换为字符串?
- ios - URL 会话保存图像
- cmake - 如何使用 CMake 构建以 ghdl 作为自定义目标的源?
- laravel - Laravel 视图进入另一个视图
- django - 清理多个 Pipenv 环境
- flutter - FormatException:JSON 中的意外字符
- java - 尝试为 4 个简单的条件制作 RegEx
- excel - 排除组合框中的重复值
- python - 使用 tarfile.extractfile 和 Python3.8 返回存档的名称而不是存档文件