提问人:Ashutosh Soni 提问时间:7/14/2023 更新时间:7/17/2023 访问量:50
如何在 kotlin 中对嵌套的对象列表进行排序并将其更新为原始列表?
How do I sort nested list of objects in kotlin and update that to the original list?
问:
所以,我有一个嵌套的 mutableList,我需要对其进行排序,但我无法让它排序。模型类如下所示:正如你所看到的,它内部有一个模型,它有 ChildrenItem 和 Children Item 可以包含在里面。
@Keep
data class ItemsItem( @field:SerializedName("children")
var children: MutableList<ChildrenItem?>? = null)
@Keep
data class ChildrenItem( @field:SerializedName("children")
var children: MutableList<ChildrenItem?>? = mutableListOf(),
)
对嵌套的 mutableList 进行排序的代码如下:
itemList.forEach { itemsItem ->
itemsItem?.children?.forEach { airportItem ->
airportItem?.children?.sortBy { it?.name }
}
}
在上面的代码中,当我下次访问itemList时嵌套的两个对象时,这里的子对象不是按名称排序的。我也尝试过CASE_INSENSITIVE方法,但它不起作用。
答:
它按预期工作:https://pl.kotl.in/D2U_9OP7f
data class ItemsItem(
var children: MutableList<ChildrenItem?>? = null
)
data class ChildrenItem(
var children: MutableList<ChildrenItem?>? = mutableListOf(),
val name: String
)
fun main() {
val itemList = listOf(
ItemsItem(
children = mutableListOf(
ChildrenItem(
name = "childItem",
children = mutableListOf(
ChildrenItem(name = "first"),
ChildrenItem(name = "second"),
ChildrenItem(name = "third"),
ChildrenItem(name = "four")
),
))
)
)
println("Before $itemList")
itemList.forEach { itemsItem ->
itemsItem.children?.forEach { airportItem ->
airportItem?.children?.sortBy { it?.name }
}
}
println("After $itemList")
}
结果:
Before [ItemsItem(children=[ChildrenItem(children=[ChildrenItem(children=[], name=first), ChildrenItem(children=[], name=second), ChildrenItem(children=[], name=third), ChildrenItem(children=[], name=four)], name=childItem)])]
在 [ItemsItem(children=[ChildrenItem(children=[ChildrenItem(children=[], name=first), ChildrenItem(children=[], name=four), ChildrenItem(children=[], name=second), ChildrenItem(children=[], name=third)], name=childItem)])] 之后
评论