//Declaring a Set as we don't want Duplicate Group Ids
Set<Id> results = new Set<Id>();
///Declaring a Map for Group with Role
Map<Id,Id> grRoleMap = new Map<Id,Id>();
//Populating the Map with RelatedID(i.e.UserRoledId) as Key
for(Group gr : [select id,relatedid,name from Group])
{
grRoleMap.put(gr.relatedId,gr.id);
}
//Groups directly associated to user
Set<Id> groupwithUser = new Set<Id>();
//Populating the Group with User with GroupId we are filtering only for Group of Type Regular,Role and RoleAndSubordinates
for(GroupMember u :[select groupId from GroupMember where UserOrGroupId='<User Id>' and (Group.Type = 'Regular' OR Group.Type='Role' OR Group.Type='RoleAndSubordinates')])
{
groupwithUser.add(u.groupId);
}
//Groups with Role
for(User u :[select UserRoleId from User where id='<User Id>'])
{
//Checking if the current User Role is part of Map or not
if(grRoleMap.containsKey(u.UserRoleId))
{
results.add(grRoleMap.get(u.UserRoleId));
}
}
//Combining both the Set
results.addAll(groupwithUser);
//Traversing the whole list of Groups to check any other nested Group
Map<Id,Id> grMap = new Map<Id,Id>();
for(GroupMember gr : [select id,UserOrGroupId,Groupid from GroupMember where
(Group.Type = 'Regular' OR Group.Type='Role' OR Group.Type='RoleAndSubordinates')])
{
grMap.put(gr.UserOrGroupId,gr.Groupid);
}
for(Id i :results)
{
if(grMap.containsKey(i))
{
results.add(grMap.get(i));
}
}
system.debug('########' + results);
000387341

We use three kinds of cookies on our websites: required, functional, and advertising. You can choose whether functional and advertising cookies apply. Click on the different cookie categories to find out more about each category and to change the default settings.
Privacy Statement
Required cookies are necessary for basic website functionality. Some examples include: session cookies needed to transmit the website, authentication cookies, and security cookies.
Functional cookies enhance functions, performance, and services on the website. Some examples include: cookies used to analyze site traffic, cookies used for market research, and cookies used to display advertising that is not directed to a particular individual.
Advertising cookies track activity across websites in order to understand a viewer’s interests, and direct them specific marketing. Some examples include: cookies used for remarketing, or interest-based advertising.