How to get values from a map apex?

4.9K    Asked by ai_7420 in Salesforce , Asked on Sep 23, 2022

I have a map passed as a parameter of an apex method. In this method I need to get the values of the map. 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}}


(Potentially, there could be more than one value)


My question is, how can I get, for example, the value of the 'ObjectName' or the value of the 'FieldName' of this map ?


Answered by alex Duncan

You may use a Map apex for this:


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));
        Map test = (Map)lines.get(key);
        System.debug('### test ' + test);
        System.debug('### test ' + test.get('ObjectName'));
    }
    return null;
}

Your Answer

Answer (1)

In Apex, you can get values from a map using the get() method or by directly accessing the map keys. Here are examples of both approaches:


Using the get() method:Map myMap = new Map();
myMap.put('key1', 10);
myMap.put('key2', 20);
Integer value1 = myMap.get('key1');
System.debug('Value for key1: ' + value1); // Output: Value for key1: 10
Integer value2 = myMap.get('key2');
System.debug('Value for key2: ' + value2); // Output: Value for key2: 20

Directly accessing the map keys:

Map myMap = new Map();
myMap.put('key1', 10);
myMap.put('key2', 20);

Integer value1 = myMap.get('key1');
System.debug('Value for key1: ' + myMap.get('key1')); // Output: Value for key1: 10
Integer value2 = myMap.get('key2');
System.debug('Value for key2: ' + myMap.get('key2')); // Output: Value for key2: 20

Both approaches will retrieve the value associated with the specified key from the map. If the key is not found in the map, the get() method will return null, so make sure to handle such cases appropriately in your code.

6 Days

Interviews

Parent Categories