How to sort a list of objects in kotlin?

Viewed 6020

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?

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

Assuming you have a class that represents your elements like this:

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

Related