Monday, 24 April 2023

Adding list of values/Records to Key using Apex Map

 

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

Tools for Lightning Web Component Development

 Below are the tools required for Web Component Development 1. Chrome Browser (Prefered) You can download it from Google 2. Visual Studio Co...