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?
If you have an object like this:
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.
Happy coding! :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With