I'm confused that something doesn't work, which I thought to be the best practise for removing duplicate SObjects from a List<SObject>.

Account a = [SELECT Id, Name FROM Account LIMIT 1];   
Map<Id, Account> accounts = new Map<Id, Account>(new List<Account>{a,a});


System.ListException: Row with duplicate Id at index

  1. How else should I do this in a one liner instead of looping over it?
  2. AND why from a conceptual standpoint does the map-way not work??

3 Answers 3


You could also use the .putAll() method to convert a list of sObjects to a map with the record Id as the key.

Account a = [SELECT Id, Name FROM Account LIMIT 1];   
List<Account> lsAccounts = new List<Account>{a,a};
Map<Id, Account> accounts = new Map<Id, Account>();
System.debug('Map:' + accounts);

The above gives the following output:

DEBUG|Map:{001i000000cyPNCAA2=Account:{Name=GenePoint, Id=001i000000cyPNCAA2}}


Found this on salesforce developer forums. Sets are by definition unique so this should work.

Set<Account> myset = new Set<sobject>();
List<Account> originalList = [SELECT Id, Name FROM Account LIMIT 1];
List<Account> result = new List<Account>();
  • I also used that as a solution. But I would also like to learn why the map way doesn't work. I believe I have seen that as a solution before. Commented Mar 6, 2015 at 8:16

Map won't work this way because Maps are a collection of key-value pair and key is always unique here. So Map won't work if ids are duplicate.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .