I need to create a Map of Sets from an SOQL query. I know that I can use something like this -
Set<Id> oppIds = new Set<Id>();
Map<Id,Set<Id>> oppIdByOppOwnerProfiles = new Map<Id,Set<Id>>();
for(Opportunity o : [SELECT Id,Opportunity.Name,OwnerId,AccountId,Owner.ProfileId
FROM Opportunity
WHERE Id IN :stage4PlusOpportunities])
{
if (oppIdByOppOwnerProfiles.keySet().contains(o.Owner.ProfileId)) {
oppIds = oppIdByOppOwnerProfiles.get(o.Owner.ProfileId);
oppIds.add(o.Id);
oppIdByOppOwnerProfiles.put(o.Owner.ProfileId,oppIds);
} else {
oppIds.add(o.Id);
oppIdByOppOwnerProfiles.put(o.Owner.ProfileId,oppIds);
}
}
but I'm wondering whether it's possible to avoid checking the Map's key, retrieving the Set, updating the Set & putting the updated Set back in the map, for every result. Can I have the query group the results into a Set & key with fewer steps?
The main reason I'm asking is because GROUP BY
appears to create a Map of collections from a query's results.
But it looks like I can't use that syntax because it requires every field that's retrieved to be grouped or aggregated. I am using the other fields from my query but I've removed that from my code, to keep it simple.