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

Groovy中使用groupBy分组并统计元素实例,实现问题修复占比计算

问题状态计数与修复占比计算方案

1. 生成目标计数映射

你当前的groupBy调用存在方法名大小写问题(Groovy中是groupBy而非groupby),且直接分组返回的是条目列表,需要进一步统计数量。可以通过嵌套分组+统计集合大小实现目标映射:

def finalDocument = [
    [problem: 'problem1', fixed: true],
    [problem: 'problem1', fixed: false],
    [problem: 'problem1', fixed: false],
    [problem: 'problem2', fixed: true],
    [problem: 'problem2', fixed: false]
]

// 先按问题分组,再对每个问题的修复状态统计数量
def countMap = finalDocument.groupBy { it.problem }.collectEntries { problem, entries ->
    [
        problem,
        entries.groupBy { it.fixed }.collectEntries { status, itemList ->
            [status, itemList.size()]
        }
    ]
}

println countMap
// 输出结果:[problem1:[true:1, false:2], problem2:[true:1, false:1]]

2. 计算修复占比

基于上面的计数映射,直接通过“修复数量/总数量”计算占比:

def repairRateMap = countMap.collectEntries { problem, statusCounts ->
    def total = statusCounts.values().sum()
    // 处理无修复记录的边界情况,避免除以0
    def repairRate = statusCounts[true] ? (statusCounts[true] / total) : 0
    [problem, repairRate]
}

println repairRateMap
// 输出结果:[problem1:0.3333333333333333, problem2:0.5]

简化写法(直接计算占比)

如果不需要中间的计数映射,可一步到位计算修复占比:

def directRateMap = finalDocument.groupBy { it.problem }.collectEntries { problem, entries ->
    def total = entries.size()
    def fixedCount = entries.count { it.fixed }
    [problem, fixedCount / total]
}

println directRateMap
// 输出结果同上

关键细节

  • Groovy集合方法为驼峰命名,注意groupBy的大小写;
  • collectEntries是将集合转换为Map的高效方式,适合分组后的二次加工;
  • count方法可直接统计符合条件的元素数量,比嵌套分组更简洁(仅需修复数量时优先使用)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 20:00:58