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

Groovy中如何遍历布尔值变量列表并打印变量名称而非值?

解决方法:获取布尔变量名并打印

你当前的代码只输出true is true,是因为创建的列表list里只保存了变量的布尔值,并没有保存变量名信息。遍历列表时只能拿到true或false,自然无法关联到对应的变量名。

要实现需求,需要把变量名和对应的值绑定在一起存储,推荐用以下两种方式:

方式一:使用Map存储(最直观)

用Map的键保存变量名,值保存对应的布尔值,遍历Map时就能同时获取名称和值:

// 定义布尔变量
def firstValue = true
def secondValue = false
def thirdValue = true

// 用Map绑定变量名与对应值
def boolMap = [
    firstValue: firstValue,
    secondValue: secondValue,
    thirdValue: thirdValue
]

// 遍历Map,判断值为true时打印变量名
boolMap.each { varName, varValue ->
    if (varValue) {
        println("${varName} is true")
    }
}

方式二:使用嵌套列表存储

如果偏好列表结构,可以把每个变量的名称和值打包成子列表,再放入主列表:

def firstValue = true
def secondValue = false
def thirdValue = true

// 每个子列表的第一个元素是变量名,第二个是对应值
def list = [
    ["firstValue", firstValue],
    ["secondValue", secondValue],
    ["thirdValue", thirdValue]
]

// 遍历列表,判断子列表的第二个元素为true时,打印第一个元素(变量名)
for (item in list) {
    if (item[1]) {
        println("${item[0]} is true")
    }
}

两种方式运行后都会输出:

firstValue is true
thirdValue is true

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 00:05:06