Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 671
Reza Faraji Avatar asked Dec 05 '25 17:12

Reza Faraji


1 Answers

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! :)

like image 168
Jose Angel Maneiro Avatar answered Dec 08 '25 05:12

Jose Angel Maneiro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!