1

From the below code, I am fetching list of records where i am getting duplicate id's..again i am passing the list to a set to avoid duplicates. Can anyone suggest a bestway to avoid duplicates in a list.

query string = select field1__c, field2__c From object1__c;
List<object1__c> obj = Database.Query(queryString);
system.debug('obj list has'+lst);
set<id> ps = new Set<id>();
for(object1__c o: obj ){
    ps.add(o.Id);
    System.debug('>>>>>>>>>>>>ps'+ ps);
}

any help is greatly appreciated.

1
  • As i know query will never return duplicate records
    – Safiya PV
    Commented Mar 30, 2017 at 9:10

1 Answer 1

7

Based on your example, if you just want Id field, query in a Map:

Map<Id, object1__c> mapObject = 
    new Map<Id, object1__c>([select field1__c, field2__c From object1__c]);

But Id's are never duplicates from a list.

So if you have any other list, just iterate over it and use map to collect it. Using Map.values method you can get back the list.

for(Object1__c obj: [select LookupField__c, field2__c From object1__c]) {
    mapObject.put(obj.LookupField__c);
}

List<Object1__c> lstUniqueRecords = mapObject.keySet();
2
  • Iam writing Query string on a child object..and getting duplicate parent id's in the list..
    – venky
    Commented Mar 30, 2017 at 7:18
  • In that case, use maps, refer second example in the answer
    – Raul
    Commented Mar 30, 2017 at 7:20

You must log in to answer this question.

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