You’ve read and written code to store data in variables. Whether it was a primitive datatype or an object like Employee, Contract, and Student, we've stored these as single data points.
Think about the code you wrote earlier for Employee. We declared multiple employees like this:
Employee jerryEmp = new Employee('Jerry'); Employee elaineEmp = new Employee('Elaine'); Employee georgeEmp = new Employee('George'); Employee kramerEmp = new Employee('Kramer');
If we wanted to represent these employees as a group - we couldn't. Until now, with Collections!
A Collection is data that’s been grouped together and given a single reference. It's an object that represents a group of other objects. These are sometimes called Data Structures. In this course, we'll go over three in-depth: List, Set, and Map.
Don't worry if the following syntax is overwhelming, we'll break it down in this course. Let's look at how we can group these employees with a List Collection.
Employee jerryEmp = new Employee('Jerry'); Employee elaineEmp = new Employee('Elaine'); Employee georgeEmp = new Employee('George'); Employee kramerEmp = new Employee('Kramer'); List<Employee> newEmployeeList = new List<Employee> {jerryEmp, elaineEmp, georgeEmp, kramerEmp};
The newEmployeeList
now groups all employees as a collection. What's the point? Well now that these are grouped, we can pass them into methods as a group. We can do this:
EmployeeController.sendWelcomeEmail(newEmployeeList);
Instead of this:
EmployeeController.sendWelcomeEmail(jerryEmp, elaineEmp, georgeEmp, kramerEmp);
If we needed a way to programmatically associate an employee's name with it's employee object - we could use a Map collection.
Map<String, Employee> newEmpMap = new Map<String, Employee>(); newEmpMap.put('Jerry', jerryEmp); // Maps Jerry to jerryEmp newEmpMap.put('Elaine', elaineEmp); // Maps Elaine to elaineEmp
You'll use collections everywhere. They're going to play a huge role in the code you write. Ever heard of "bulkification" or "bulkifying" code? That's how it's done!
By the time you're done with this course, you'll be one step closer to mastering Apex!