Tag Archives: Randomize

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;
}