How to remove duplicates from list in Salesforce?

Create a map instead of list and finally insert or update the map values.

Sample Code:

Map<Id, Account> mapAccount = new Map<Id, Account>();

for(Account acc : listAccount){
...............
...............
mapAccount.put(acc.Id, acc);
}

update mapAccount.values();

6 comments:

  1. Why We need to do all these things.. Simply do like this
    List Listacc= [select id,name from account];
    Set Unique= New Set();
    Unique.addall(Listacc);

    plz correct me, if i am wrong..

    ReplyDelete
    Replies
    1. This is also correct!!!

      Delete
    2. Hi,

      I'd like to one line it

      Set Unique = new Set ([select id from Account]);

      Or for DML, from a duplicated list:
      update (new Map (oppList)).values();

      Naore

      Delete
    3. Correction:
      update (new Map (oppToUpdate)).values();

      Delete
  2. account id always unique what about account name but its not unique so then how to make list of account name to be unique so if use set how to know that the string values are equal then I need to give custom error how please let me know

    ReplyDelete
    Replies
    1. Use Map < String, String > and use containsKey() in map to find whether already the map contains the same name.

      Use Duplicate management to avoid creating duplicate records - http://www.infallibletechie.com/2015/05/duplicate-management-in-salesforce.html

      Delete