如何对Kotlin中的嵌套对象列表进行排序并将其更新为原始列表?

rqdpfwrv  于 2023-08-07  发布在  Kotlin
关注(0)|答案(1)|浏览(118)

所以,我有一个嵌套的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方法,但它不起作用。

ijxebb2r

ijxebb2r1#

它按预期工作: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")
}

字符串
测试结果:
在[ItemsItem(children=[ChildrenItem(children=[],name=first),ChildrenItem(children =[],name=second),ChildrenItem(children=[],name=third),ChildrenItem(children=[],name =four)],name= childrenItem)]之前
在[ItemsItem(children=[ChildrenItem(children=[],name=first),ChildrenItem(children =[],name=four),ChildrenItem(children=[],name=second),ChildrenItem(children=[],name=third)],name= childrenItem)]之后

相关问题