function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
cyber surfer 18cyber surfer 18 

iterating List values through a another List values

Hi All,

I have a requirement where I am required to search if a field from list<customobject> contains any one value from anoher list.

here the field is a LongTextArea hence i am not able to use any formula , as i have long list of Keywords which i need to check i have written below logic.

String alp ;
List<String> lstAlpha =  new List<String>{'Keyword 1','Keyword 2','Keyword 3'}; // List of Keywords to be searched
integer i = 0;
System.debug('List Values--->'+lstAlpha);
List<Abc__c> lst = [SELECT id,name,LongTextAreafield__c from Abc__c where status = 'open'];
for( Abc__c ls:lst)
{
    alp = ls.LongTextAreafield__c;
    // iterating one list in another
    do {
        if (alp.contains(lstAlpha[i])) // checking 1st list field contains keyword or not
        {system.debug ('Check Successfull');  }
        System.debug('Value of i =====>>>>'+i);
        i++;
    }
    while (i < lstAlpha.size());
    // I can use any loop but as its not best practice I want to aviod nested loops

}
system.debug ('alp contents ==== '+alp);


Issue here is I had to use Nested loops which is not best practice can anyone suggest a better solution to this requirement?

 
Abhijith E 4Abhijith E 4
Hey There,

You can use Sets  instead here..
 
Set<String> alphaSet =  new Set<String>{'Keyword 1','Keyword 2','Keyword 3'}; // List of Keywords to be searched

List<Abc__c> abcList = [SELECT id,name,LongTextAreafield__c from Abc__c where status = 'open']; //Retrive Data
    //Iterate over the Data
    if (!abcList.isEmpty()) {
        for( Abc__c abcObj : abcList) {
            //If the long text area if not Empty execute the logic
            if (String.isNotBlank(abcObj.LongTextAreafield__c)) {
                //Create a set of all the values in long text area field
                Set<String> existingKeyWordSet = new Set<String>();
                existingKeyWordSet.addAll(abcObj.LongTextAreafield__c.split(' ').remove(null));
                //Create a buffer set for comparison
                Set<String> bufferSet = new Set<String>();
                bufferSet.addAll(existingKeyWordSet);
                bufferSet.retainAll(alphaSet);
                //Check if there was at least one overlapping value
                if (!bufferSet.isEmpty()) {
                    System.debug('Match Found for the record'+abcObj.Id);
                } else {
                    System.debug('Match NOT Found for the record'+abcObj.Id);
                }
            }
        }
    }

Hope this helps!!