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

如何在Groovy脚本中使用Lambda表达式?求转换指定Java代码为Groovy版本

转换后的Groovy脚本版本

基础兼容版(保留原代码判断逻辑)

if (CollectionUtils.isNotEmpty(orderModel.getFreeProductSets())) {
    orderModel.getFreeProductSets().each { orderFreeProductSetModel ->
        if (CollectionUtils.isNotEmpty(orderFreeProductSetModel.getFreeProducts())) {
            modelService.removeAll(orderFreeProductSetModel.getFreeProducts())
        } else {
            println "no entry found for orderFreeProductSetModel"
        }
    }
    modelService.removeAll(orderModel.getFreeProductSets())
} else {
    println "FreeProductSets is empty"
}

Groovy简化版(利用语法糖优化)

如果你的Groovy环境支持属性访问(符合JavaBean规范的getter会自动映射为属性),可以用更简洁的写法:

if (orderModel.freeProductSets) {
    orderModel.freeProductSets.each { setModel ->
        if (setModel.freeProducts) {
            modelService.removeAll(setModel.freeProducts)
        } else {
            println "no entry found for orderFreeProductSetModel"
        }
    }
    modelService.removeAll(orderModel.freeProductSets)
} else {
    println "FreeProductSets is empty"
}

转换说明

  • 用Groovy原生的each闭包替代Java的forEach+Lambda表达式,这是Groovy遍历集合的标准写法,兼容性更好
  • Groovy允许省略语句末尾的分号,代码更简洁
  • 简化版中利用Groovy的布尔判断特性:空集合、null对象在条件判断中会被视为false,可以替代CollectionUtils.isNotEmpty的调用;同时直接用属性名(如freeProductSets)替代getFreeProductSets()方法调用,是Groovy的惯用写法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 21:55:26