比较Kotlin中的两个对象
我刚刚开始学习 Kotlin。我有两个对象,我需要比较它们。我只想要更改名称的汽车列表(我想在数据库中使用新值更新车库对象,当它更改时)
对象一:
{
"name": "Tom's garage"
"brands": [
{
"name": „Volkswagen”,
"cars": [
{
"id": „1”,
„name”: „Golf”
},
{
"id": „2”,
„name”: „Tiguan”
}
]
},
{
"name": „Audi”,
"cars": [
{
"id": „3”,
„name”: „A3”
},
{
"id": „4”,
„name”: „A4”
}
]
}
]
}
对象二:
{
"name": "Tom's garage"
"brands": [
{
"name": „Volkswagen”,
"cars": [
{
"id": „1”,
„name”: „Golf”
},
]
},
{
"name": „Audi”,
"cars": [
{
"id": „3”,
„name”: „A5””
},
]
}
]
}
所以在输出中,我只想要车库中更名的汽车列表(奥迪 A3 到奥迪 A5)。
[
{
"name": „Audi”,
"cars": [
{
"id": „3”,
„name”: „A5””
},
]
}
]
这就是我写的,但我对我的代码不满意。你能建议我更好的 kotlin 解决方案吗?
fun findDiff(current: Garage, updated: Garage): List<Car> {
val carsMap = current.brands.map {
brand -> brand.name to brand.cars.map { car -> car.id to car }.toMap()
}.toMap()
val output = arrayListOf<Car>()
for (brand in updated.brands) {
for (car in brand.cars) {
currentSettingsMap[brand.name]?.get(car.id)?.
let { currentCar ->
if (currentCar.name != car.name) {
output.add(car)
}
}
}
}
return output
}
模型:
class Garage(
val name: String
val brands: List<Brand> = emptyList()
)
class Brand(
val name: String,
val cars: List<Car> = emptyList()
)
class Car(
val id: Int,
val name: String
)
这是学习的例子,没有任何意义。
回答
fun findDiff(current: Garage, updated: Garage): List<Car> {
// preparing a map for fast search
val currentCars = current.brands
.flatMap { it.cars } // list of all cars in "current" garage
.associateBy { it.id } // car.id -> car
return updated.brands.asSequence()
.flatMap { it.cars } // list of all cars in "updated" garage
.filter { it.id in currentCars } // we remove cars that are not in the "current" garage
.filter { it.name != currentCars.getValue(it.id).name } // filtering cars with the same id and different names
.toList()
}