You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按自定义名称顺序对findLoot对象列表进行排序?

按自定义列表顺序对物品列表排序

要实现按mappingOfLootList指定的顺序对findLoot列表排序,核心思路是让每个物品的排序依据对应它在自定义列表中的索引值,按索引从小到大排序即可。具体实现如下:

优化查找效率(推荐)

直接调用mappingOfLootList.indexOf(it.name())每次都会遍历列表,物品数量较多时效率偏低。建议先把自定义列表转成名称到索引的映射Map,将查找索引的时间复杂度降到O(1):

// 生成物品名称到排序优先级(索引)的映射
private val lootPriorityMap = mappingOfLootList.withIndex()
    .associate { (index, name) -> name to index }

执行排序

根据需求选择原地排序或生成新列表:

  • 原地排序(直接修改原findLoot列表):
findLoot.sortBy { lootPriorityMap[it.name()] ?: Int.MAX_VALUE }
  • 生成新列表(原列表保持不变):
val sortedLoot = findLoot.sortedBy { lootPriorityMap[it.name()] ?: Int.MAX_VALUE }

代码说明

  • lootPriorityMap[it.name()]获取当前物品在自定义列表中的索引,该索引即为排序优先级;
  • ?: Int.MAX_VALUE用于处理不在自定义列表中的物品:将它们的优先级设为最大值,会排在所有指定物品的后面。若想让这类物品排在最前面,可替换为Int.MIN_VALUE。

完整示例

// 自定义排序顺序列表
private val mappingOfLootList = listOf("Draconic visage", "Onyx bolt tips", "Coins", "Nature rune", "Shield left half", "Dragon med helm",
        "Rune 2h sword", "Dragon spear", "Rune kiteshield", "Rune battleaxe", "Rune sq shield", "Rune full helm", "Rune longsword",
        "Rune spear", "Rune med helm", "Adamant platebody", "Lava battlestaff", "Rune axe", "Adamant 2h sword", "Fire orb", "Runite bar",
        "Dragonstone", "Tooth half of key", "Loop half of key", "Grimy ranarr weed", "Rune javelin", "Blood rune", "Runite bolts", "Rune dart",
        "Death rune", "Law rune", "Silver ore", "Lava dragon bones", "Black dragonhide", "Rune arrow", "Grimy avantoe", "Grimy kwuarm",
        "Grimy cadantine", "Uncut diamond", "Adamantite bar", "Rune knife", "Grimy lantadyme", "Grimy dwarf weed", "Fire talisman")

// 生成优先级映射
private val lootPriorityMap = mappingOfLootList.withIndex()
    .associate { (index, name) -> name to index }

// 原地排序方法,替换YourItemClass为实际物品类名
fun sortLoot(findLoot: MutableList<YourItemClass>) {
    findLoot.sortBy { lootPriorityMap[it.name()] ?: Int.MAX_VALUE }
}

// 生成新排序列表的方法
fun getSortedLoot(findLoot: List<YourItemClass>): List<YourItemClass> {
    return findLoot.sortedBy { lootPriorityMap[it.name()] ?: Int.MAX_VALUE }
}

内容的提问来源于stack exchange,提问作者TheDeverino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 04:52:44