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

如何在Karate中统计列表重复值?karate.distinct()报错求助

在Karate中统计列表重复值的解决方案

方法1:遍历列表直接统计次数

通过遍历目标列表,维护一个计数Map来记录每个元素的出现次数,示例代码如下:

* def list = [
  "Cloud Services - Hybrid and Azure",
  "Cloud Services - Hybrid and Azure",
  "Cloud Services - Hybrid and Azure",
  "Cloud Services - Hybrid and Azure",
  "Application Development",
  "Application Development",
  "Application Development",
  "CAB Approval"
]
* def countMap = {}
* karate.forEach(list, function(item){
    countMap[item] = (countMap[item] || 0) + 1
  })
* print countMap

执行后会输出包含各元素出现次数的Map,其中"Cloud Services - Hybrid and Azure"对应的值即为4。

方法2:结合HashSet去重后统计

你之前用HashSet获取唯一值的思路可行,但写法有误,正确的实现方式如下:

* def list = [
  "Cloud Services - Hybrid and Azure",
  "Cloud Services - Hybrid and Azure",
  "Cloud Services - Hybrid and Azure",
  "Cloud Services - Hybrid and Azure",
  "Application Development",
  "Application Development",
  "Application Development",
  "CAB Approval"
]
* def uniqueItems = new java.util.HashSet(list)
* def countMap = {}
* karate.forEach(uniqueItems, function(item){
    countMap[item] = karate.filter(list, function(x){ return x == item }).length
  })
* print countMap

这段代码先通过HashSet得到所有唯一元素,再逐个统计每个元素在原列表中的出现次数。

关于karate.distinct()的说明

karate.distinct()仅用于返回列表的去重结果,不负责统计次数。如果使用时报错,需确认传入的参数是标准JSON数组,正确用法示例:

* def distinctList = karate.distinct(list)
* print distinctList // 输出 ["Cloud Services - Hybrid and Azure", "Application Development", "CAB Approval"]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 10:55:17