如何根据ID合并两个对象列表? [英] How to merge two lists of objects based on IDs?
问题描述
我有两个列表.一个称为 oldList
并包含旧数据,第二个称为 updateList
并包含一组更新.
I have two lists. One is called oldList
and contains old data, the 2nd one is called updateList
and contains a set of updates.
我想使用这些规则创建一个新列表:
I want to create a new list with those rules:
- 从
oldList
中获取所有数据 - 使用唯一的
id
附加所有更新 - 如果
oldData
中已经存在更新项目的id
,请替换
- take all data from the
oldList
- append all updates with unique
id
- if
id
of an updated item already exists inoldData
, replace it
我想出了一个简单的代码:
I came up with a simple code:
Item.kt
data class Item (val id: String, val text: String)
Main.kt
fun main() {
val oldList: List<Item> = listOf(
Item("aaa1", "aaa2"),
Item("bbb1", "bbb2"),
Item("ddd1", "ddd2"))
val updateList: List<Item> = listOf(
Item("aaa1", "aaa3"),
Item("ccc1", "ccc2"))
val resultList = oldList.toMutableList()
for (item in updateList) {
val index = oldList.indexOfFirst { it.id == item.id }
if (index < 0) {
resultList.add(item)
} else {
resultList[index] = item
}
}
println(resultList)
}
这很好用,但我可以想象它效率低下,并且可能还有一些不错的 Kotlin
习惯用法.有更好的解决方案吗?
This works fine but I can imagine it's inefficient and there might also be some nice Kotlin
idiom. Is there a better solution?
推荐答案
如果原始顺序无关紧要,则可以合并列表,将新值放在第一位,以便在 distinctBy
中使用它们致电:
If the original order doesn't matter, you can combine the lists, putting the new values first to favor them in a distinctBy
call:
val resultList = (updateList + oldList).distinctBy(Item::id)
如果顺序完全符合您的描述,则可以在合并它们之前将两个列表都转换为地图.当使用 +
组合到Maps时,第二个Map中的项目优先,但是保留第一个Map中的顺序.
If the order matters exactly as you described it, you can convert both lists to maps before combining them. When combining to Maps with +
, the items in the second Map take precedence, but the order from the first Map is preserved.
val resultList =
(oldList.associateBy(Item::id) + updateList.associateBy(Item::id)).values.toList()
这篇关于如何根据ID合并两个对象列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!