Tag Archives: List

Get All List Values From A Map To A Single List

Sample Code:

//Map with Country Key and City values
Map<String, List<String>> objMap = new Map<String, List<String>>();

List<String> usaCityList = new List<String>{'New York', 'Los Angeles', 'Chicago', 'San Diego'};
objMap.put('USA', usaCityList);

List<String> indiaCityList = new List<String>{'New Delhi', 'Mumbai', 'Chennai', 'Bangalore'};
objMap.put('India', indiaCityList);

//Get All cities in a single list variable
List<String> objCityList = new List<String>();
for (List<String> obj : objMap.values()){
    objCityList.addAll(obj);
}
System.debug('objCityList-' + objCityList);

Use Like With List And Set Collections In SOQL Queries

Set Collection in Like:

Set<String> accountNames = new Set<String>{'%Sam%', '%App%', '%Len%','%Nok%'};
List<Account> accList = [Select Id, Name From Account Where Name LIKE :accountNames];

List Collection in Like:

List<String> accountNameList = new List<String>{'%Sam%', '%App%', '%Len%','%Nok%'};
List<Account> accList = [Select Id, Name From Account Where Name LIKE :accountNameList];

Shuffle or Randomize a List in Apex

Sample Code:

public static List<Account> getRandomAccountList(List<Account> accList){
    
    Account acc;
    integer randomIndex;
    integer currentIndex = accList.size();
    
    while (currentIndex != 0) {
        randomIndex = integer.valueOf(Math.floor(Math.random() * currentIndex));
        currentIndex -= 1;
        acc = accList[currentIndex];
        accList[currentIndex] = accList[randomIndex];
        accList[randomIndex] = acc;
    }
    return accList;
}

Convert List to Set in Salesforce

Sample Code:

//List of string variable
List<String> objList = new List<String>();
//Set of string variable
Set<String> objSet = new Set<String>();

objList.add('A');
objList.add('B');
objList.add('C');  

//Use addAll() to add list of string to Set
objSet.addAll(objList);

//Or Use Set Constructor
Set<String> objSetData = new Set<String>(objList);