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

Groovy:如何从Map列表中筛选ArrayList指定颜色的车辆ID

解决方案

你代码的问题在于:对findAll返回的List直接调用.id时,Groovy默认只会取列表第一个元素的id属性,而非所有元素的。要提取所有匹配车辆的ID,需要用collect方法遍历筛选后的列表,逐个取出id。

正确实现代码

def paint = ["blue", "green", "red"]
def cars = [[color:"black", year:2018, id: 1345], [color:"blue", year:2009, id: 1241], [color:"green", year:2009, id: 1525], [color:"yellow", year:2009, id: 1891]]

// 筛选出颜色匹配的车辆,再收集所有id
def resultIDs = cars.findAll{ it.color in paint }.collect{ it.id }

println resultIDs // 输出 [1241, 1525]

代码说明

  1. cars.findAll{ it.color in paint }:正确筛选出所有颜色在paint列表中的车辆Map,得到包含两个元素的List。
  2. .collect{ it.id }:遍历筛选后的每个车辆Map,提取其中的id值,最终返回一个包含所有匹配ID的ArrayList。

如果需要将ID转为逗号分隔的字符串(比如"1241,1525"),可以在collect后调用join(","):

def resultIDStr = cars.findAll{ it.color in paint }.collect{ it.id }.join(",")
println resultIDStr // 输出 "1241,1525"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 17:36:23