We can add records to the list directly using the "add" method but while coming to add list or values/records to a key we need to use map<id,list<subject>>.
Below is the sample code:
Map<Id, List<user>> mapUserRoleToUsers = new Map<Id, List<user>>();
for(User userRec : [SELECT UserRoleId FROM User LIMIT 50000]) {
//Checks if the User Role Id is already added to key or not
if(mapUserRoleToUsers.containsKey(userRec.UserRoleId)) {
List<user> usersRecs = mapUserRoleToUsers.get(userRec.UserRoleId);
usersRecs.add(userRec);
mapUserRoleToUsers.put(userRec.UserRoleId, usersRecs);
} else {
mapUserRoleToUsers.put(userRec.UserRoleId, new List<user> { userRec });
}
}
From the above code you can get all the user records based on the user role id.
No comments:
Post a Comment