0

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';
      Second__c='Nine,Four,Second,Six';

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>();
lstFirst=obj.First__c.split(',');
for(String s : lstFirst){
     if(s.contains(obj.Second__c){
        ----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 ??

2 Answers 2

2

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(',') {
    if(value2.contains(s)
      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>();
lstFirst=obj.First__c.split(',');
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 (,).

2
  • No these are Custom picklist, I hope spliting on ( , ) is true ! Commented Sep 30, 2014 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
    Commented Sep 30, 2014 at 23:58
2

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(','));
intersection.retainAll(obj.Second__c.split(','));

You must log in to answer this question.

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