0

I am trying to build a map<String, List<Id>> where the List<Id> is the list of UserOrGroupId field in the GroupMember Object that has similar Group.DeveloperName values and that I wish to put in the key

I have a list of group Members List<GroupMember> groupMemberList And I am confused on how to fill my map when looping through the list of group members Any tips or hints on how I can this work ?

2 Answers 2

3

Iterate GroupMember records and group UserOrGroupId by unique Group.DeveloperName

List<GroupMember> groupMemebrs = [
    SELECT Id, GroupId, Group.DeveloperName, UserOrGroupId
    FROM GroupMember
    LIMIT 50000
    ];
Map<String, List<Id>> groupMemebersByGroupDeveloperName = new Map<String, List<Id>>();
for(GroupMember groupMember :groupMemebrs){
    List<Id> userGroupIds = new List<Id>();
    if(groupMemebersByGroupDeveloperName.containsKey(groupMember.Group.DeveloperName)){
        userGroupIds = groupMemebersByGroupDeveloperName.get(groupMember.Group.DeveloperName)
    }
    userGroupIds.add(groupMember.UserOrGroupId);
    groupMemebersByGroupDeveloperName.put(groupMember.Group.DeveloperName, userGroupIds);
}

result is stored in Map groupMemebersByGroupDeveloperName

2
  • But the groupMemebersByGroupDeveloperName is empty ! how are we supposed to check its key Sep 30, 2021 at 8:49
  • 1
    @ismailkartit It is populated by the loop; we create a new List or get the existing List, add the Id to the List, and then put it in the Map.
    – sfdcfox
    Sep 30, 2021 at 9:31
0

You are never really assigning any values to userGroupIds... if the map contains the key you are just setting the list to equal the list from before... and also during each iteration of the loop your list will be cleared out as a new list because you added userGroupIds = new List that will execute each loop so there will be no value in the list and if the map contains the developer name you are just assigning it to the value that is stored in the map and then adding the groupId then putting it in the map... there is a simpiler and easier way this is how I usually handle these types of data types..

if (!groupMembersByDevName.containsKey(groupMember.Id)) { groupMembersByDevName.put(groupMember.Id,new List{groupMember.UserOrGroupId}); } else { groupMembersByDevName.get(groupMember.Id).add(groupMember.UserOrGroupId); }

if the map does not contain the groupMember key then it will add the memberGroup to the map and assign a new list with only one element in it.. and if the map does contain the groupMember key it will simply add the user/group id to the list

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .