[SalesForce] Check if there is any common string in Two List, or in Picklists

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

Best Answer

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 (,).

Related Topic