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

如何在Groovy中基于指定优先级对字母数字列表进行排序

Groovy实现按指定优先级列表排序需求

核心逻辑说明

  • 先将预定义的三个静态列表存储为字典映射,方便根据传入的优先级参数快速调取对应的优先级元素集合,转成Set类型是为了提升元素存在性判断的效率
  • 按输入列表的原有顺序,拆分出属于优先级列表的元素、不属于优先级列表的元素两部分
  • 两组元素直接顺序拼接即为最终输出结果,完全保留原列表非优先级元素的排列顺序

完整代码实现

// 预定义静态列表映射
def staticListMap = [
    a: ["z1", "a2", "x4", "n7", "v10"] as Set,
    b: ["l3","b10", "b1", "f5", "y23"] as Set,
    c: ["l2", "c12", "d15", "n17", "c1"] as Set
]

// 排序工具方法
def sortByPriority(List inputList, String priority) {
    // 可选:增加优先级参数合法性校验
    if (!staticListMap.containsKey(priority)) {
        throw new IllegalArgumentException("非法优先级参数:${priority},仅支持a/b/c")
    }
    def targetPrioritySet = staticListMap[priority]
    // 按原顺序拆分优先级元素和其他元素
    def priorityElements = inputList.findAll { it in targetPrioritySet }
    def otherElements = inputList.findAll { !(it in targetPrioritySet) }
    // 拼接返回结果
    return priorityElements + otherElements
}

测试验证

使用示例参数运行测试:

def Input_list = ["f5", "y23","z1", "a2","l2", "c12"]
def Priority = "c"
def Output_list = sortByPriority(Input_list, Priority)
println Output_list
// 运行输出:[l2, c12, f5, y23, z1, a2],和预期结果完全匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 23:15:02