[英]How to sort a list of objects in kotlin?
I have a list of objects like this:我有一个这样的对象列表:
[
{
"Price": 2100000,
"Id": "5f53787e871ebc4bda455927"
},
{
"Price": 2089000,
"Id": "5f7da4ef7a0ad2ed730416f8"
},
{
"Price": 0,
"Id": "5f82b1189c333dab0b1ce3c5"
}
]
How can I sort this list by price value of objects and then pass it to my adapter?如何按对象的价格值对该列表进行排序,然后将其传递给我的适配器?
Assuming you have a class that represents your elements like this:假设您有一个 class 代表您的元素,如下所示:
data class Element (
val price: Int,
val id: String
)
And given a list of those from your deserializer:并给出来自您的反序列化器的列表:
val listOfElements: List<Element> = ...
You can obtain a new list sorted by price as follows:您可以获得按价格排序的新列表,如下所示:
val sortedByPrice = listOfElements.sortedBy { it.price }
Try it in the Kotlin Playground: https://pl.kotl.in/TBIdxsaoi在 Kotlin 游乐场尝试: https://pl.kotl.in/TBIdxsaoi
If you have an object like this:如果您有这样的 object:
class YourClass(
val price: Int,
val id: String
)
You can sort by price in two ways:您可以通过两种方式按价格排序:
Mutable可变的
val yourMutableList: MutableList<YourClass> = mutableListOf()
yourMutableList.sortBy { it.price }
// now yourMutableList is sorted itself
Not mutable不可变
val yourList: List<YourClass> = listOf()
val yourSortedList: List<YourClass> = yourList.sortedBy { it.price }
As you can see, in the second sample, you have to save the result in a new list.如您所见,在第二个示例中,您必须将结果保存在新列表中。 Because List is immutable, therefore it cannot be altered and it is necessary to create a new list .
因为List是不可变的,所以它不能被改变,需要创建一个新的 list 。
Happy coding: :)快乐编码::)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.