kotlin中的排序和分组

问题描述 投票:0回答:1

我在Kotlin中有一个对象列表,我想按数字然后按字符串对它们进行排序。有没有办法做到这一点?我浏览了数百篇文章,但任何地方都无济于事。

myList.sortedWith(compareBy<Item> {it.name.id }.thenBy{it.name.secondname})此代码无效。

当然myList是项的类型。

问候

sorting kotlin comparable
1个回答
0
投票

myList.sortedWith(compareBy<Item> {it.name.id }.thenBy{it.name.secondname})返回列表的排序后的副本,但不会修改原始列表。

如果要修改原始列表,则可以使用sortWith代替sortedWith

myList.sortWith(compareBy<Item> { it.name.id }.thenBy { it.name.secondname })

或重新分配myList变量:

myList = myList.sortedWith(compareBy<Item> { it.name.id }.thenBy { it.name.secondname })
© www.soinside.com 2019 - 2024. All rights reserved.