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 advanced concepts such as list sorting, object hash code and more.

Types of Collections in Apex Salesforce

The collection is the type of variables 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

List Set Map
A list is an ordered collection A set is an unordered collection A map is a collection of key-value pairs
Can contain Duplicate Do not contain any duplicate Each 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.

Object

All Apex classes and primitives inherit from Object.

Collection in Apex

Collections: List, Set and Map

List Set Map
Usage Ordered list of non-unique elements Unordered collection of unique elements Dictionary of key values
Compatibility Some interoperable constructors and methods (addAll, containsAll...) Some interoperable constructors and methods (addAll, containsAll...) -
Equality-checks uses equals() uses hashCode() then, equals() uses hashCode() then, equals()
Sortable yes no no
Iterable yes yes no

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 = it.next();    // Do something }

Iterators benefits:

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

Iterators and Collection Locking

List<Integer> myList = new List<Integer> {1,2,3}; Iterator<Integer> it = myList.iterator();  it.next(); //1 it.next(); //2 it.next(); //3  // Fails mylist.add(4);// System.FinalException  //Works it = null; myList.add(4);

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(); }; myList.sort(); // System.ListException : One or more of the items in this list is not Comparable

Exceptions

  • 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

Recording

Check this session for more details.

..