How do I check if an element is in a set apex?

933    Asked by Ayushigupta in Salesforce , Asked on Sep 22, 2022

I wrote a method last night that creates a new custom object record that is related to an Account and a User. it works great however, it breaks when there is an already existing record for a user. After research I think I need a set to compare if the user value already exists then not run the logic.


I can't get the syntax right to compile and see if it works. Example code:


public static void createNPDAccountTeam(Map accOwner)
{
    List npdAccTeamToInsert = new List();
    Set existingAccTeam = new Set();
    existingAccTeam.addAll([SELECT Id, User__c, Account__c FROM NPD_Account_Team__c WHERE Account__c IN: accOwner.keySet()]);
    for(Id accId : accOwner.keySet())
    {
        if(!existingAccTeam.contains(accId.User__c)
        {
            npdAccTeamToInsert.add(new NPD_Account_Team__c(
                Account__c = accId,
                User__c = accOwner.get(accId),
                Role__c = 'Custom',
                Team_Member_Status__c = 'Active'
                ));
        }
    }
    insert npdAccTeamToInsert;
}
I get the error on line 10:
Unexpected token '{'
What am I doing wrong? I know that it does not need a ; at the end of the if line but I am not sure why it will not save.
Answered by Ayushi gupta

To check if an element is in set apex, please close the if condition with extra parens.


if(!existingAccTeam.contains(accId.User__c))
{
}

Your Answer

Interviews

Parent Categories