Master in Salesforce Apex collection

Working with collections like List, Map and Set is part of every day’s routine for Apex developer. While their basic use is straightforward, there are some advanced quirks that can get you to the next level. Join us in this session to learn about how to Master in Salesforce Apex collection concepts such as list sorting, object hash code and more.

Types of Collections in Apex Salesforce

The collection is the type of variable that can store multiple numbers of records. It can increase and decrease dynamically.

  1. List 
  2. Map
  3. Set

Let see the different between the all collection

A list is an ordered collectionA set is an unordered collectionA map is a collection of key-value pairs
Can contain DuplicateDo not contain any duplicateEach unique key maps to a single value. Value can be duplicate

When we should use map over list and set?

Master in Apex collection

While their basic use is straightforward, there are some advanced quirks that can get you to the next level. Join us in this session to learn about advanced concepts such as list sorting, object hash code and more.


All Apex classes and primitives inherit from Object.

Master in Salesforce Apex collection

Collections: List, Set and Map

UsageOrdered list of non-unique elementsUnordered collection of unique elementsDictionary of key values
CompatibilitySome interoperable constructors and methods (addAll, containsAll…)Some interoperable constructors and methods (addAll, containsAll…)
Equality-checksuses equals()uses hashCode() then, equals()uses hashCode() then, equals()

Collection Casting

lets see below example how to cast the collection in Salesforce.

Class Parent{}
Class Child extents Parent {}

// Valid List casting
List<Child> childList = new List<Child>();
List<Parent> parentList = childList;

// Valid Map casting
Map<String, Child> childMap = new Map<String, Child>();
Map<String, Parent> parentMap = childMap;

// Invalid Set casting
Set<Child> childSet = new Set<Child>();
Set<Parent> parentSet = childSet; // Illegal assignment

Equals() vs hashCode()

Lets understand the different between Equals() and HashCode().

Integer hashCode()

Pseudo-unique hash code value for an object instance Required when working with Set/Map, faster than equals() Returns same value for two “equals()” objects Changes when a property value is changed.

Boolean equals(Object o)

Compares types and field values Not used in Set/Map methods unless hashCode collision

Iterators and Iterable Interfaces

List and Set implement Iterable.

Iterators and Iterable Interfaces

Iterators at Work

List<Account> myList = new List<Account>();
Interator<Account> it =myList.iterator();
while ( it.hasNext()){
   Account acc =;
   // Do something

Iterators benefits:

  • provides read-only access to collection
  • locks collection in read-only mode
  • dynamically calculate collection elements on the go

Apex Iterators and Collection Locking

List<Integer> myList = new List<Integer> {1,2,3};
Iterator<Integer> it = myList.iterator();; //1; //2; //3

// Fails
mylist.add(4);// System.FinalException

it = null;

Sorting in Apex Collections

The first choice when it comes to sorting things in Apex is generally to write a SOQL query with an ORDER BY clause. However, sometimes you need to sort records without fetching them from the database or even sort objects that are not records. In those cases, you use the List.sort method.

Working with the Comparable interface

List.sort() works with list elements that implement the Comparable interface. The interface specifies a single method.

compareTo Return following values

  • 0 if this instance and other are equal
  • >0 if this instance is greater than other
  • <0 if this instance is less than other

Sorting Objects That Don’t Implement Comparable

Runtime error when calling List.sort() method. As a word of Waring, it’s safe to have objects that don’t implement in a list but if you call the method on that list, you’ll get an exception:

class SomeClass {}

List<SomeClass> myList = new List<SomeClass>{
  new SomeClass(), new SomeClass();
// System.ListException : One or more of the items in this list is not Comparable


  • Primitive types
  • sObject types

Default Primitive Ordering: Natural Ordering

The sorting algorithm form can sort any mix of object with various types as long as they all implements . For instance, you could perfectly write something like this

Sort rule:

  1. Type sorting (except Boolean)
  2. value sorting (numerical, lexicographic, chronological…)

Example: null < Boolean false < Integer < Double < Boolean true < Long < Date < String

Default sObjects Ordering

  1. Label of the sObject type
  2. Name field, if applicable
  3. Standard fields except Id and Name
  4. Custom fields

Sorting with Comparators

Problem: List.sort() is limited

  • ordering logic is tied to the Comparable object
  • can’t sort with different strategies and parameters

Solution: work with a custom Comparator pattern

Master in Salesforce Apex collection Video

YouTube video


I hope this session helped you to become a Master in Salesforce Apex collection.

Amit Chaudhary
Amit Chaudhary

Amit Chaudhary is Salesforce Application & System Architect and working on Salesforce Platform since 2010. He is Salesforce MVP since 2017 and have 17 Salesforce Certificates.

He is a active blogger and founder of Apex Hours.

Articles: 460

Leave a Reply

Your email address will not be published. Required fields are marked *