2

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});

throws

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??
5

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>();
accounts.putAll(lsAccounts);
System.debug('Map:' + accounts);

The above gives the following output:

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

4

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>();
myset.addAll(result);
result.addAll(myset);
  • 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. – Robert Sösemann Mar 6 '15 at 8:16
2

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.

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.