1

I have a list of contact id's in a text field named members. They are comma separated. What would be the best way to check if there are duplicate id's?

Thanks

1
  • How is this field populated?
    – nicolas
    Jul 17, 2016 at 6:36

2 Answers 2

2

You can use Set collection:

Represents a collection of unique elements with no duplicate values.

string members = '001C000001DgWjDIAV,001C000001DgWjEIAV,001C000001DgWjDIAV';

set<string> memberIds = new set<string>();
for (String str :members.split(',')){
    memberIds.add(str);
}

String uniquemembers = JSON.serialize(memberIds).replaceAll('["\\[\\]]','');
system.debug(members);
system.debug(uniquemembers);

23:58:32:003 USER_DEBUG [9]|DEBUG|001C000001DgWjDIAV,001C000001DgWjEIAV,001C000001DgWjDIAV
23:58:32:003 USER_DEBUG [10]|DEBUG|001C000001DgWjDIAV,001C000001DgWjEIAV
4

Starting from Ilya's answer but making use of the Set and List constructors available and the very useful String.join method gives you this code:

String csv = '001C000001DgWjDIAV,001C000001DgWjEIAV,001C000001DgWjDIAV';
List<String> l = new List<String>(new Set<String>(members.split(',')));
String uniqueCsv = String.join(l, ',');

You must log in to answer this question.

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