如何在 kotlin 中对对象列表进行排序?

Rez*_*aji 16 sorting android list kotlin

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

 [
    {
      "Price": 2100000,
      "Id": "5f53787e871ebc4bda455927"
    },
    {
      "Price": 2089000,
      "Id": "5f7da4ef7a0ad2ed730416f8"
    },
    {
   
      "Price": 0,
      "Id": "5f82b1189c333dab0b1ce3c5"
    }
 ]
Run Code Online (Sandbox Code Playgroud)

如何按对象的价格值对该列表进行排序,然后将其传递给我的适配器?

Jos*_*iro 27

如果你有一个这样的对象:

class YourClass(
  val price: Int,
  val id: String
)
Run Code Online (Sandbox Code Playgroud)

您可以通过两种方式按价格排序:

可变的

val yourMutableList: MutableList<YourClass> = mutableListOf()
yourMutableList.sortBy { it.price }
// now yourMutableList is sorted itself
Run Code Online (Sandbox Code Playgroud)

不可变

val yourList: List<YourClass> = listOf()
val yourSortedList: List<YourClass> = yourList.sortedBy { it.price }
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,在第二个示例中,您必须将结果保存在新列表中。由于List是不可变的,因此它不能被更改需要创建一个新的 List

快乐编码!:)

  • 您可以先保存列表,然后对其进行排序。例如: **List&lt;SameProduct&gt; sameProducts = item.sameProducts as ArrayList&lt;SameProduct&gt;**,然后将列表排序在适配器中, **productStoresAdapter.stores = sameProducts.sortedBy { it.Price }** (2认同)