Search code examples
salesforcesalesforce-lightning

How to check if a Map contains a given value in Apex Salesforce?


When raising this question to https://chat.openai.com/chat, this source of info suggests that I can use a method myMap.contains() with the following example:

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

// Check if the map contains the value 2
Boolean containsValue = map.containsValue(2); // returns true

// Check if the map contains the value 4
containsValue = map.containsValue(4); // returns false

But when checking Salesforce soap api for class Map, I do not see any .containsValue() method: https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_map.htm#apex_System_Map_methods

So, I think that the AI of https://chat.openai.com/chat might be wrong.

How can I verify, with apex, if a given value is contained in a Map?

Thank you.


Solution

  • Map has a values() method that returns a List containing every value in the map.
    If you have to check only one value, you could just call contains() on that list, while if you have to check multiple values you should create a new Set with those values then call contains() (or containsAll()).

    Map<String, Integer> myMap = new Map<String, Integer>();
    myMap.put('key1', 1);
    myMap.put('key2', 2);
    myMap.put('key3', 3);
    
    List<Integer> mapValues = myMap.values();
    System.debug(mapValues.contains(1)); // true
    
    Set<Integer> mapValueSet = new Set<Integer>(mapValues);
    System.debug(mapValueSet.contains(2)); // true
    System.debug(mapValueSet.contains(5)); // false
    

    Keep in mind that List.contains() runs in linear time (O(n)) while Set.contains() runs in constant time (O(1)).