I have two multiselect picklists Assume -

First__c and Second__c

I want to check if there is any common string between them

e.g. First__c = 'First,Second,Third';

Here 'Second' this string is selected in both the picklists.

YES I CAN DO IT USING FOR LOOP and spliting string like -

List<String> lstFirst= new List<String>();
for(String s : lstFirst){
        ----My Task-------

but since I have too many such picklists I dont want to use for loops and if() which will increase my LOC and Nested for's since this logic goes in between other code.

Any Suggestions ??


You're pretty much going to have to use one of those techniques as you need to split at least one of the lists into values to search for.

If you're concerned about complexity it seems to me that you should be using another method to do this search. Take the code you've got and wrap it in a nice utility function so that it can be called simply:

boolean FindSharedValue(String value1, String value2) {
  for(String s : value1.split(',') {
      return true;
  return false;

Then call it like so:

if(HasSharedValue(obj.First__c, obj.Second__c)
    ----My Task-------

It seems you're worried about the wrong things, simple refactoring can take care of complexity and make code easy to read.

Also notice how you can simplify some of the code you posted by doing away with temporary variables (and also not creating a new list which gets discarded anyway):

// this
List<String> lstFirst= new List<String>();
for(String s : lstFirst){

// becomes
for(String s : obj.First__c.split(',')){

Finally, if these are standard picklists you should be splitting on ;, not on a comma (,).

  • No these are Custom picklist, I hope spliting on ( , ) is true ! – Salesforce Steps Sep 30 '14 at 7:32
  • By 'standard' I meant 'platform' picklists. Even if it's a custom field of a picklist type it'll use semicolons to delimit the options. – Matt Lacey Sep 30 '14 at 23:58

This should be possible without any for loop by utilizing a little bit of set theory.

  1. Split both lists into distinct sets
  2. The intersection of both sets is your answer

In code:

Set<String> intersection = new Set<String>(obj.First__c.split(','));

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.