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

遍历水果列表实现匹配打印是否存在更优的实现方法?

代码优化方案

你当前使用的是Groovy语法,多独立if判断的写法虽然功能可实现,但存在硬编码耦合高、新增水果类型需要额外新增if分支的问题,推荐以下两种更易维护的实现方式:

方案1:映射表实现(推荐,扩展性最强)

提前把水果和对应的输出前缀绑定为映射关系,后续新增水果只需要更新映射表即可,不需要修改遍历逻辑:

def fruits = ["apple", "orange", "pineapple"]
// 水果-输出前缀映射表
def fruitPrefix = [
    "orange": "A delicious",
    "pineapple": "Another delicious",
    "apple": "More delicious"
]

fruits.each { fruit ->
    if (fruitPrefix.containsKey(fruit)) {
        println("${fruitPrefix[fruit]} ${fruit}")
    }
}

方案2:switch语句替换多if

如果水果类型固定不会频繁变动,也可以用switch语句替换多if判断,逻辑层级更清晰:

def fruits = ["apple", "orange", "pineapple"]

for (fruit in fruits) {
    switch(fruit) {
        case "orange":
            println("A delicious ${fruit}")
            break
        case "pineapple":
            println("Another delicious ${fruit}")
            break
        case "apple":
            println("More delicious ${fruit}")
            break
    }
}

另外注意你原代码中println("More delicious ${fruit}"})多写了一个多余的右大括号,实际运行会触发语法错误,上述优化方案已经修正了该问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 04:42:03