基于另一个列表顺序对对象列表进行排序Kotlin

bwleehnv  于 2023-08-06  发布在  Kotlin
关注(0)|答案(2)|浏览(153)

我有一个模型叫做限制

data class Restrictions(
   val info: List<AccountInfo>,
   val displayOrder: List<Display>
)

// info field
data class AccountInfo(
   val name: String,
   val code: String,
   val target: Int
)

// Shows the targetText and a description (key, value)
data class Display(
   val key: String,
   val value: String
)

// Target appears in a Enum class
enum class Target(val target: Int, val targetText: String) {
    Target0(0, "NA"),
    Target1(1, "T1"),
    Target2(2, "T2"),
    Target5(5, "T5"),
    Target7(7, "T6");

    // Here function like getTargetByTargetText and similar...

}

字符串
在一个http响应之后,我得到了一个限制模型,如下所示

Restrictions(
  info {
     AccountInfo("name1", "code1", 1),
     AccountInfo("name2", "code2", 1),
     AccountInfo("name3", "code3", 1),
     AccountInfo("name4", "code4", 2),
     AccountInfo("name5", "code5", 2),
     AccountInfo("name6", "code6", 5),
     AccountInfo("name7", "code7", 5)
  },
  displayOrder {
     Display("T5", "Account blocked"),
     Display("T1", "Account closed"),
     Display("T2", "Account opened")
  }
)


所以,我现在想做的是,根据“target”字段对信息列表进行排序,但是基于displayOrder.key字段。例如,上述输入的结果应为

AccountInfo("name6", "code6", 5),
     AccountInfo("name7", "code7", 5),
     AccountInfo("name1", "code1", 1),
     AccountInfo("name2", "code2", 1),
     AccountInfo("name3", "code3", 1),
     AccountInfo("name4", "code4", 2),
     AccountInfo("name5", "code5", 2)


如何使用Kotlin做到这一点?

ecbunoof

ecbunoof1#

val targets = Target.values().associate { it.targetText to it.target }
val displayOrder = restrictions.displayOrder.map { targets[it.key] }
val result = restrictions.info.sortedBy { displayOrder.indexOf(it.target) }

字符串
在KotlinPlayground上试试:https://pl.kotl.in/Bf8gffj4i

jecbmhm3

jecbmhm32#

你可以这样做(假设displayOrder包含有效且完整的列表):

private val targetToText = Target.values().associate { it.target to it.targetText }

// ...

val accounts: List<AccountInfo> = ...
val displayOrder: List<Display> = ...

val targetTextToPriority = displayOrder.mapIndexed { index, display -> display.key to index }.toMap()

accounts.sortedBy { info -> targetTextToPriority[targetToText[info.target]] }

字符串
技巧是构建一个永久的MaptargetCode(Int)到targetText(String),并将targetText(String)Map到它在提供的Display的列表中的顺序。然后你可以比较任意两个AccountInfo。如果你想在同一个目标中对AccountInfo进行排序,你可以改进sortedWith

相关问题