dictionarysalesforceapex

Reading data from a Map of sObjects in Apex Salesforce


Please see my code below. I am able to create a Map. I do not know how to read the values in the collection of records that are part of the Value in the Map.

Please help.

List<OrderDestinationItem__c> ordersOfAllUsers = new List<OrderDestinationItem__c>();

ordersOfAllUsers = [SELECT CreatedById, Id, CreatedDate, OrdStatus__c, Total_Line_Amount__c From OrderDestinationItem__c  Where CreatedDate > 2024-04-10T07:27:52.000+0000 and Total_Line_Amount__c > 20];

Map<Id, List<OrderDestinationItem__c>> usersOrdersMap = new Map<Id, List<OrderDestinationItem__c>>();

for ( OrderDestinationItem__c currentOrderedItem : ordersOfAllUsers){
    if (!usersOrdersMap.containsKey(currentOrderedItem.CreatedById)){
        usersOrdersMap.put(currentOrderedItem.CreatedById, new List<OrderDestinationItem__c>{currentOrderedItem});
    } else {
        usersOrdersMap.get(currentOrderedItem.CreatedById).add(currentOrderedItem);
    }
}

Solution

  • Once you have your Map ready one way to loop through it all would be with keyset()

    for(Id userId : usersOrdersMap.keyset()){
        List<OrderDestinationItem__c> temp = usersOrdersMap.get(userId);
        System.debug('User ' + userId + ' has ' + temp.size() + ' items';
        // System.debug(temp);
    }