0

Whenever i run this code in console all duplicate record are checked .

I need those record ,if duplicate name(record) is greater than 1 than mark it as checked. (i.e if two record of same name then 1 should be marked or if three record of same name 2 record should be marked)

List<AggregateResult> acc=[SELECT Name accname,  Prospect_Code__c  , COUNT(Id) ids FROM Account where Id Not
                           In (Select AccountId from Contact) And Id Not In (Select AccountId from Opportunity)                           
                           GROUP BY Name, Prospect_Code__c  HAVING count(Id)>1];

Map<String,List<Account>> act = new Map<String,List<Account>>(); // add list item to map
List<Account> actLst = new List<Account>();

List<Account> accList = [SELECT Name , duplicate__c FROM Account where Id Not
                           In (Select AccountId from Contact) And Id Not In (Select AccountId from 
                         Opportunity) ];


for(Account acc : accList)
{
    if(!act.containsKey(acc.Name))
        {
            act.put(acc.Name,new List<Account>{acc});
        }
    else 
        {
            act.get(acc.Name).add(acc);
        }

}


for(AggregateResult aggres : acc)
{
    if(act.containsKey((String)aggres.get('accname')))
    actLst.addAll(act.get((String)aggres.get('accname')));

    System.debug('AccName'+aggres.get('accname'));
}

if(actLst.size() >  0   )
{
for(Account a : actLst)
{

    a.duplicate__c = true;
}
system.debug('actLst >> ' + actLst);
update actLst;
}
0

The code above can be written much easier and shorter.

Your duplicate records lie in toUpdate list.

First of all, make selection, then you need to remember names, that have already been used. Therefore, the first record with nor used name updates set, all that goes after it need to be updated as duplicates.

List<Account> accounts = [SELECT Name, duplicate__c FROM Account];
Set<String> userNames = new Se<String>();
List<Account> toUpdate = new List<Account>();

for (Account account_i : accounts) {
    if(!userNames.contains(account_i.Name)) {
        userNames.add(account_i.Name);
    } else {
        account_i.duplicate__c = true;
        toUpdate.add(account_i);
    }
}

update toUpdate;
  • 2
    Even shorter: if(!usernames.add(account_i.name)) { account_i.duplicate__c = true; toUpdate.add(account_i); } The add method returns false if the set was not modified (e.g. if contains(value) would return true before adding the value). – sfdcfox Jun 21 at 13:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.