gpt4 book ai didi

android - 如何对kotlin中的对象列表进行排序?

转载 作者:行者123 更新时间:2023-12-04 23:52:32 25 4
gpt4 key购买 nike

我有一个这样的对象列表:

 [
{
"Price": 2100000,
"Id": "5f53787e871ebc4bda455927"
},
{
"Price": 2089000,
"Id": "5f7da4ef7a0ad2ed730416f8"
},
{

"Price": 0,
"Id": "5f82b1189c333dab0b1ce3c5"
}
]
如何按对象的价格值对该列表进行排序,然后将其传递给我的适配器?

最佳答案

如果你有这样的对象:

class YourClass(
val price: Int,
val id: String
)
您可以通过两种方式按价格排序:
可变
val yourMutableList: MutableList<YourClass> = mutableListOf()
yourMutableList.sortBy { it.price }
// now yourMutableList is sorted itself
不可变
val yourList: List<YourClass> = listOf()
val yourSortedList: List<YourClass> = yourList.sortedBy { it.price }
如您所见,在第二个示例中,您必须将结果保存在新列表中。因为 列表 是不可变的,因此它 无法更改 有必要创建一个新列表 .
快乐编码! :)

关于android - 如何对kotlin中的对象列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67061626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com