Skip to content

Instantly share code, notes, and snippets.

@emoran
Last active April 27, 2022 14:30
Show Gist options
  • Save emoran/4ea945ec3db32cc8c06b to your computer and use it in GitHub Desktop.
Save emoran/4ea945ec3db32cc8c06b to your computer and use it in GitHub Desktop.
Adding list values to apex map<String,List<Sobject>>
Map<Id, List<Id>> userRoleToUsers = new Map<Id, List<Id>>();
for(User newUser : [SELECT UserRoleId FROM User LIMIT 50000]) {
if(userRoleToUsers.containsKey(newUser.UserRoleId)) {
List<Id> usersId = userRoleToUsers.get(newUser.UserRoleId);
usersId.add(newUser.Id);
userRoleToUsers.put(newUser.UserRoleId, usersId);
} else {
userRoleToUsers.put(newUser.UserRoleId, new List<Id> { newUser.Id });
}
}
@Lorenzo8912
Copy link

Is it the same?

@pathakarchit
Copy link

Hi @emoran, can you please elaborate as of how can we use the list values in Map<Id, List> to create a new record for each id in the List in the Map?

@emoran
Copy link
Author

emoran commented Feb 18, 2020

Hi @Lorenzo8912 @pathakarchit, sorry for leaving this, I will create a small sample and comment the code for better undesrtanding.

@mukeshtiwaricode
Copy link

mukeshtiwaricode commented Sep 23, 2021

I think we can write above code as below:

    Map<Id, List<Id>> userRoleToUsers = new Map<Id, List<Id>>();
    for(User newUser : [SELECT UserRoleId FROM User LIMIT 50000]) {
        if(userRoleToUsers.containsKey(newUser.UserRoleId)) {
            userRoleToUsers.get(newUser.UserRoleId).add(newUser.Id);
        } else {
            userRoleToUsers.put(newUser.UserRoleId, new List<Id> { newUser.Id });
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment