function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ayan SarkarAyan Sarkar 

Getting SOQL results into MAP

For example... I have a SOQL query :-

[SELECT name, profile.name, email, isActive from User where UserRoleId in (SELECT ID from UserRole WHERE name in ('CEO','COO','ALC Midwest','ALC Southwest'))];

Now each role may have more than one users.

So, My requirement is that I want a map with key = UserRoleID and value = list of all users under that role.

So is it possible to do this without looping the above query's result and then putting values into map

Or some GROUP BY clause (or something else) can help me do this efficiently..

If nothing is possible and only looping is the only way then please provide an efficient and optimized code than the normal one-by-one row looping.

Help me its urgent
Best Answer chosen by Ayan Sarkar
Rahul SharmaRahul Sharma
Its simple and can be done using single query, What was the problem you were facing while implementing it?
See if following code helps.
Map<Id, List<User>> mapUserRole = new Map<Id, List<User>>();
for(User objUser: [SELECT Name, UserRoleId, Profile.Name, Email, isActive FROM User
    WHERE UserRoleId IN (SELECT Id FROM UserRole WHERE Name IN ('CEO','COO','ALC Midwest','ALC Southwest'))]) {
    if(!mapUserRole.containsKey(objUser.UserRoleId)) {
        mapUserRole.put(objUser.UserRoleId, new List<User>{objUser});
    } else {
        mapUserRole.get(objUser.UserRoleId).add(objUser);
    }
}
system.debug(mapUserRole);

 

All Answers

Rahul SharmaRahul Sharma
Its simple and can be done using single query, What was the problem you were facing while implementing it?
See if following code helps.
Map<Id, List<User>> mapUserRole = new Map<Id, List<User>>();
for(User objUser: [SELECT Name, UserRoleId, Profile.Name, Email, isActive FROM User
    WHERE UserRoleId IN (SELECT Id FROM UserRole WHERE Name IN ('CEO','COO','ALC Midwest','ALC Southwest'))]) {
    if(!mapUserRole.containsKey(objUser.UserRoleId)) {
        mapUserRole.put(objUser.UserRoleId, new List<User>{objUser});
    } else {
        mapUserRole.get(objUser.UserRoleId).add(objUser);
    }
}
system.debug(mapUserRole);

 
This was selected as the best answer
Ayan SarkarAyan Sarkar
Actually I was thinking of using Group By in SOQL query (if possible) so that no for loop required.