public class Utility {
public static Set < Id > fetchUserIdsOfPublicGroup( Id groupId ) {
Set < Id > userIds = new Set < Id >();
Set < Id > groupIds = new Set < Id >();
groupIds.add( groupId );
do {
Set < Id > tempGroupIds = new Set < Id >();
for ( GroupMember objGM : [ SELECT UserOrGroupId FROM GroupMember WHERE GroupId IN: groupIds AND Group.Type = ‘Regular’ ] ) {
String strUserOrGroupId = objGM.UserOrGroupId;
if ( strUserOrGroupId.startsWith( ‘005’ ) )
userIds.add( objGM.UserOrGroupId );
else
tempGroupIds.add( objGM.UserOrGroupId );
}
groupIds = tempGroupIds;
} while ( groupIds.size() > 0 );
return userIds;
}
}
To Test,
Id groupId = ’00G4x000001BVLH’;
If there are multiple Nested groups associated to the Group, there are more chances of hitting Apex CPU Time Limit or 101 SOQL limit.