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)).

Answer from RubenDG on Stack Overflow
Discussions

apex - How to check if a field value contains a value from map - Salesforce Stack Exchange
I have a map that is populated with list, and also list collection from task object. How do update the task that is retrieved from the query based on certain conditions? Map More on salesforce.stackexchange.com
🌐 salesforce.stackexchange.com
Using Maps in Apex (beginner)
I’ve been learning Apex for a little bit now and have a pretty novice understanding of how it all works, but the concept I’m struggling with the most is using maps instead of lists or sets. Does anyone have good reference material or examples on when Map is useful/what’s really happening in the background? I feel like I’m really close to fully grasping it, but there’s still something missing where I’m not fully understanding the value... More on reddit.com
🌐 r/salesforce
7
4
September 23, 2020
apex - How to find a Map key (with possible contains text)? - Salesforce Stack Exchange
I have custom metadata records in the format: If I store these Key and Values in a Map, how to have a conditional 'contains' check for the auxiliary word: Apartment_1 Use-case: I will need to co... More on salesforce.stackexchange.com
🌐 salesforce.stackexchange.com
December 16, 2019
How to display Map's list value based on 1 key in Apex Salesforce? - Stack Overflow
Hello beautiful people, I have a scenario where I am defining a Map with string key and a list. Now, I want to put values in a list one by one and also display them using the single Key. Example co... More on stackoverflow.com
🌐 stackoverflow.com
🌐
JanBask Training
janbasktraining.com › community › salesforce › how to get values from a map apex?
How to get values from a map apex? | JanBask Training Community
September 23, 2022 - Here is the apex method : @AuraEnabled public static String manageFilters(Map · lines){ System.debug('### lines : ' + lines); System.debug('### lines.values() : ' + lines.values()); for(String key : lines.keySet()){ System.debug('### lines.get(key) : ' + lines.get(key)); System.debug('### >>> ' + lines.get(key)); } return null; } The map lines is not null and contains some values, here is what I can see in the system debug of lines : {0={FieldName=AccountId, ObjectName=Opportunity, Operator=<, Value=dfg}}
Top answer
1 of 1
1

Rather than loop through for loop, you should add that lstSubIssues in the query.

You don't need to create separate Map for this lists, Since for subIssue1, Subject_Details__c = 'Registration', similarly for subIssue2, twh.Subject_Details__c = 'Activation'.

After getting the list of Task, loop though the tasks and use subIssue1.contains(twh.SubIssue__c) to find the matching values and then update accordingly.

Note: Don't try to hardcode RecordtypeId, rather use from metadata.

Here is entire code:

List<String> subIssue1 = new List<String>{'Issue Uploading Docs (KTP)',
                                           'Issue Uploading Docs (KK)',
                                           'Issue Uploading Docs (NPWP)',
                                           'Issue Uploading Docs (All)',
                                           'Wrong Docs Request to re-submit (KTP)',
                                           'Wrong Docs Request to re-submit (NPWP)',
                                           'Wrong Docs Request to re-submit (KK)'};
List<String> subIssue2 = new List<String>{'Member Activation Request (Manager)',
                                          'Member Activation Request (VP)',
                                          'Member Activation Request (TL)'};
List<String> lstSubIssues = new List<String>();
lstSubIssues.addAll(subIssue1);
lstSubIssues.addAll(subIssue2);                   

List<Task> taskWithSub = [SELECT Id, SubIssue__c, CustomerHappiness__c, Subject_Details__c 
FROM Task 
WHERE RecordTypeId = '<recordTypeId>' 
AND SubIssue__c IN:lstSubIssues  
AND Subject_Details__c = 'It has been changed'  ];

if(!taskWithSub.isEmpty()){
    for(Task twh : taskWithSub){
        if(subIssue1.contains(twh.SubIssue__c)) {
            twh.Subject_Details__c = 'Registration';
        }
        if(subIssue2.contains(twh.SubIssue__c)) {
            twh.Subject_Details__c = 'Activation';
        }  
    } 

    update taskWithSub; //here update
}
🌐
SaaS Guru
saasguru.co › salesforce-map-class
Salesforce Map Class: Comprehensive Guide
May 24, 2024 - Gain valuable knowledge and hands-on experience to excel in this ever-evolving platform. The Salesforce Map Class is a data structure in Apex that stores key-value pairs, allowing efficient data management and retrieval.
🌐
SFDC Kid
sfdckid.com › 2019 › 04 › salesforce-apex-collection-map.html
APEX COLLECTION: Map - SFDC Kid
In this Episode, we are going to discuss the last but one of the very important salesforce apex collection i.e. Map. So let's get started, A Map is a collection of key-value pairs where each unique key maps to a single value.
🌐
S2 Labs
s2-labs.com › home › map initialization methods in apex
Map Initialization Methods In Apex | Salesforce Developer Tutorials
April 27, 2026 - Yes, we can initialize a map using SOQL if the map key is Id and the value is an sObject type. Salesforce automatically uses each record's ID as the key and the record itself as the value. Maps are used in Apex primarily to enable fast, efficient lookups by key, including record IDs without writing nested loops.
Find elsewhere
🌐
Deepika Khanna
mytutorialrack.com › home › understanding map methods in apex: key concepts and best practices
Understanding Map Methods in Apex: Key Concepts and Best Practices
June 1, 2023 - In Apex, the Map class provides a collection of key-value pairs, where each key is unique. It offers several methods to manipulate and retrieve data from the map. Map methods in Apex provide a wide range of functionality, including searching ...
🌐
CRS Info Solutions
crsinfosolutions.com › home › detailed guide to contains method in salesforce apex
Detailed Guide to Contains Method in Salesforce Apex
Salesforce Training - In Salesforce Apex, the contains method is a powerful tool used to check whether a String, List, Set, or Map contains a specific element. This method evaluates whether the specified value exists within the collection and returns a Boolean result. I have enrolled for Salesforce Admin and development online course at CRS info solutions. It’s really the best training i have ever taken and syllabus is highly professional
Rating: 5 ​
🌐
Salesforcepoint
salesforcepoint.com › 2020 › 07 › salesforce-apex-map-map-methods-with.html
Salesforce Apex Map & Map methods with Examples | Salesforce Lightning Web Components, Aura Components, Apex Triggers, Apex REST API Integration
First of all Map is a key and value pair i.e each and every value is associates with key. Here key is unique, that means if we put one key,value pair into Map, we should not add same key one more time.
🌐
Salesforce
trailhead.salesforce.com › trailblazer-community › feed › 0D54V00007T4DWPSA3
Getting map value with contains key - Trailhead - Salesforce
Skip to main content · Bring your team and maximize your impact at Dreamforce. Register three or more to unlock $999 passes
🌐
Decodeforce
decodeforce.com › blogs › apex-map-class-methods-and-examples
Salesforce apex map class and methods with practice examples
Maps in Salesforce Apex are collections of key-value pairs. The keys are unique, and each key maps to a specific value.
🌐
JanbaskTraining
janbasktraining.com › home › salesforce maps: features, benefits & methods
Salesforce Maps: Features, Benefits & Methods
December 29, 2022 - A map is a collection of key-value pairs where each unique key maps to a single value. Map keys can be any primitive data type like string, integer,decimal, Id while values can be a primitive, sObject, collection type or an Apex object.
🌐
Reddit
reddit.com › r/salesforce › using maps in apex (beginner)
r/salesforce on Reddit: Using Maps in Apex (beginner)
September 23, 2020 - Each key has a value, though the value may be null. Each key must be unique. If a Map already contains a particular key, you can't add that key again with a different value.
🌐
Stack Exchange
salesforce.stackexchange.com › questions › 288511 › how-to-find-a-map-key-with-possible-contains-text
apex - How to find a Map key (with possible contains text)? - Salesforce Stack Exchange
December 16, 2019 - //Retrieving from CMD List<String> auxiliaryList = new List<String>(); List<CustomMetadata__mdt> myCMDRecords = [Select Id, Auixliary__c, Value__c From CustomMetadata__mdt]; if(!myCMDRecords .isEmpty( )) { valueDevNames = new Set<String>(); for(CustomMetadata__mdt rec : myCMDRecords ){ auxiliaryList.add(rec.Auixliary__c); valueDevNames.add(rec.Value__c) } //Creating a map of Queues if(!auxiliaryList.isEmpty()){ queueMap = new Map<Id, Group>([Select Id, Name From Group Where Type = 'Queue' And Name = :auxiliaryList]); } } //Implementation logic Set<Id> caseIdSet = new Set<Id>(); if(!queueMap.isEmpty() && !valueDevNames.isEmpty()){ for(Case caseRec: [Select Id, OwnerId, RecordType.DeveloperName From Case Where Id IN : passedCaseIds]){ if(queueMap.containsKey(caseRec.OwnerId) && valueDevNames.contains(caseRec.RecordType.DeveloperName)){ caseIdSet.add(caseRec.Id); } } } apex · map ·
🌐
CRS Info Solutions
crsinfosolutions.com › home › what is a map class in salesforce apex? with examples
What is a Map class in Salesforce Apex? with examples
Salesforce Training - Using Null Keys: Apex does not allow null keys in a map. Attempting to use a null key will result in a runtime exception. Always check for null before using a value as a key. Overwriting Values Unintentionally: Because adding an item with an existing key will overwrite the current value associated with that key, it’s important to check if a key already exists if overwriting is not intended. You can use the containsKey... I have enrolled for Salesforce Admin and development online course at CRS info solutions. It’s really the best training i have ever taken and syllabus is highly professional
Rating: 5 ​
Top answer
1 of 4
28

containsKey and get have the same performance characteristics. The majority of the CPU time used will be within the hashCode and equals methods for the objects used as keys. Poorly designed keys will have poor performance characteristics, particularly when you're Using Custom Types in Map Keys and Sets.

In practice, I've found that the majority of the time, you'll need to use the results that you get back from the map, so it is important that you cache the results of get so that you're not using containsKey or get more frequently than necessary. In other words, the optimal design choice usually look like this:

// Replace "Object" with the appropriate data type
Object value = someMap.get(key);
if(value != null) {
    // Do something with value
}

This pattern means you won't need to call both containsKey and get, which reduces CPU time, sometimes significantly. As I stated above, make sure that, if you're using custom types for keys, that non-equal values return unique hashCode values.

For example, this is a bad key design:

public class Key {
    public Integer hashCode() {
        return 1;
    }
    public Boolean equals(Object o) {
        return o === this;
    }
}

This is because the number of equals methods that will be called is up to the number of elements in the set or map key set, which can easily be hundreds of times more costly than an optimal key design:

public class Key {
    static Integer counter = 0;
    Integer code;
    public Key() {
        code = counter++;
    }
    public Integer hashCode() {
        return code;
    }
    public Boolean equals(Object o) {
        return o === this;
    }
}

By returning unique hashCode values for values which are not equal, you'll drastically improve the performance of both get and containsKey.

Keep in mind that most of the time, you don't care if a map contains a particular key, you care about the value being returned having a null value (to avoid NullPointerException). It is incredibly rare that you'll ever only care about the presence of a key in a map (containsKey), and it is extremely common that you'll care about NullPointerException.

So, in conclusion, I would say that the most efficient design pattern will almost always be to cache the results of get, and not use containsKey. containsKey is almost always just a CPU sink, wasting precious CPU cycles when you're just going to be calling get anyways. It takes approximately the same amount of time to call get and containsKey, and it's virtually guaranteed that after you call containsKey, you're going to call get anyways, so you may as well cut out the middle man.

If you write code that ever only uses containsKey and doesn't use get, you should be using a Set, not a Map. If you're using containsKey and get, you're probably using a sub-optimal algorithm. You should call get no more than once per key for optimal performance.

The rare case for using containsKey used to be when initializing lists or sets in maps, like this:

Map<Id, Contact[]> contacts = new Map<Id, Contact[]>();
for(Contact record: [SELECT AccountId FROM Contact]) {
    if(contacts.containsKey(record.AccountId)) {
        contacts.get(record.AccountId).add(record);
    } else {
        contacts.put(record.AccountId, new List<Contact> { record });
    }
}

However, in the past year or so, I've designed an even more optimal design:

Contact[] temp;
Map<Id, Contact[]> contacts = new map<Id, Contact[]>();
for(Contact record: [SELECT AccountId FROM Contact]) {
    if((temp = contacts.get(record.AccountId)) == null) {
        contacts.put(record.AccountId, temp = new Contact[0]);
    }
    temp.add(record);
}

While you'll want to add comments to explain this, this solution combines a null check with caching to produce optimal CPU usage. When you want to aggregate data together this way, this combined caching strategy outperforms any other design I've written seen or used by a large margin, particularly when you need the performance boost in triggers.

2 of 4
20

Don't get hung up on efficiency: clear code is always the first priority. If containsKey is clearer use that. If you want to use the value from the map (so it mustn't be null) use the get with a null check.

This provides an example of a null map value where the methods give different results:

Map<String, Object> m = new Map<String, Object>{'abc' => null};
// This outputs false
System.debug(m.get('abc') != null);
// This outputs true
System.debug(m.containsKey('abc'));