Play Games

Search This Blog

Friday, September 24, 2021

How to compare values of 2 different lists in apex - Salesforce Globe For You

How to compare values of 2 different lists in apex - Salesforce Globe For You

Problem: I have 2 lists ,listA with some values and listB with some values.I need to compare listA and listB and return true if both are same else false.

Sample Code:

List<String> listA = new List<String>{'a','b','d','c'};

listA.sort();

List<String> listB = new List<String>{'a','d','b','c'};

listB.sort();

Boolean bBothListAreSame = false;

if(listA.size() == listB.size()) {

    Boolean bBothSame = true;

    for(integer i = 0; i<listA.size(); i++) {

        if(listA[i] != listB[i]) {

            bBothSame = false;  

        }

    }

    if(bBothSame == true) {

        bBothListAreSame = true;

    } 

        

} else {

    bBothListAreSame = false;

}

system.debug('Both Lists are same:'+bBothListAreSame);

Output:



How to convert comma separated string to a list in apex - Salesforce Globe For You

How to convert comma separated string to a list in apex - Salesforce Globe For You

Problem: I have a string as a;b;c;d.and I want to convert that string value to array as new List<String>{'a','b','c','d'}

Sample Code:

String s = 'a;b;c;d';

List<String> lstAlphabet = new List<String>();

lstAlphabet = s.split(';');

System.debug('List is:::'+lstAlphabet);

Output:



How to convert array(list) to a string with values separated with semicolon in apex - Salesforce Globe For You

How to convert array(list) to a string with values separated with semicolon in apex - Salesforce Globe For You

Problem: I have one list lstAlphabet as List<String> lstAlphabet = new List<String>{'a','b','c','d'}

I want to convert that list to string as a;b;c;d

Sample Code:

String strFinalString = '';

List<String> lstAlphabet = new List<String>{'a','b','c','d'};

for(String aphabet : lstAlphabet) {

    if(!string.ISEMPTY(strFinalString)) {

        strFinalString = strFinalString+';'+aphabet;

    } else {

        strFinalString = aphabet;

    }

}

system.debug('Final String:::'+strFinalString);

Output: