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

如何在Salesforce Apex中检查Map是否包含指定值?ChatGPT方法存疑

在Salesforce Apex中检查Map是否包含指定值

Apex的Map类确实没有containsValue()方法,ChatGPT的回复存在错误。以下是两种可靠的实现方式:

方法一:利用values()集合的contains()方法

Map.values()方法会返回包含所有值的List,而Apex的List类提供了contains()方法,可以直接判断目标值是否存在:

Map<String, Integer> numMap = new Map<String, Integer>();
numMap.put('key1', 1);
numMap.put('key2', 2);
numMap.put('key3', 3);

// 检查是否包含值2
Boolean hasValue2 = numMap.values().contains(2); // 返回true
// 检查是否包含值4
Boolean hasValue4 = numMap.values().contains(4); // 返回false

这种方式实现简单,适合单次或少量查询的场景,时间复杂度为O(n)(n为Map的元素数量)。

方法二:构建反向Map(优化频繁查询)

如果需要多次检查值的存在性,为了提升查询效率,可以预先构建一个以值为键的反向Map:

Map<String, Integer> numMap = new Map<String, Integer>();
numMap.put('key1', 1);
numMap.put('key2', 2);
numMap.put('key3', 3);
numMap.put('key4', 2); // 处理值重复的情况

// 构建反向Map,值对应多个键时用List存储
Map<Integer, List<String>> reverseMap = new Map<Integer, List<String>>();
for (String key : numMap.keySet()) {
    Integer value = numMap.get(key);
    if (!reverseMap.containsKey(value)) {
        reverseMap.put(value, new List<String>());
    }
    reverseMap.get(value).add(key);
}

// 检查值是否存在
Boolean hasValue2 = reverseMap.containsKey(2); // 返回true
Boolean hasValue4 = reverseMap.containsKey(4); // 返回false

这种方式的后续查询时间复杂度为O(1),但需要额外内存存储反向Map,适合频繁查询值存在性的场景。如果Map中的值是唯一的,反向Map的value可以直接使用单个键类型(无需List)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 00:55:31