Skip to content

Instantly share code, notes, and snippets.

@matthewholliday
Last active April 22, 2019 17:03
Show Gist options
  • Save matthewholliday/25c1be65528ce0b4a012c89f06fcabbd to your computer and use it in GitHub Desktop.
Save matthewholliday/25c1be65528ce0b4a012c89f06fcabbd to your computer and use it in GitHub Desktop.
Get Random Records in Apex
Integer sampleSize = 50;
//Testing functions by printing out names from sample db.
List<Contact> population = [SELECT LastName FROM Contact LIMIT 1000];
List<Contact> sample = getContactSample(population,sampleSize);
System.debug('sample size: ' + sample.size());
for(Contact sampledContact : sample){
System.debug('Contact: ' + sampledContact.LastName);
}
public List<Contact> getContactSample(List<Contact> population, Integer sampleSize){
List<Contact> sample = new List<Contact>();
for(Integer i = 0; i < sampleSize; i++){
//Get index of a random contact from the population.
Integer indexOfContact = getRandomNumber(population.size() - sample.size());
//Add contact to sample.
sample.add(population[indexOfContact]);
//Remove contact from population.
population.remove(indexOfContact);
}
return sample;
}
public Integer getRandomNumber(Integer ceiling){
return Integer.valueof((Math.random() * ceiling));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment