Wednesday, September 12, 2018

Collection in salesforce

In Apex, collections can be of three types: Lists, Sets, and Maps. While there is no specific limit on the number of items a collection can hold, there is a general limit on heap size.

1) List: An ordered collection of elements that can contain duplicates. You can access elements using an index.

2) Set: An unordered collection of unique elements. It doesn't allow duplicates, and the order of elements is not guaranteed.

3) Map: A collection of key-value pairs. Each key is unique, and it maps to a specific value. You can quickly retrieve values based on their keys.

Each of these collections serves different purposes based on the needs of your program.

List:
  1.  List is an ordered collection of element.
  2.  Can store duplicate 
  3.  We can perform dml operations on list
Syntax:

To declare a list, use the List keyword followed by the primitive data, sObject, nested list, map, or set type within <> characters. For example:
  • list<object> listName=new list<object>();     // List of any object.
  • list<String> listName=new list<String>();    // List of string.
Structure of list is shown below:

Location:   Index 0   Index 1  Index 2   Index 3  Index 4
Values:          1                   2              3               4         3


Methods available with list are:

get(index)

It is used for accessing element from list.

add(listElement)

It is used for adding element to the end of  list

add(index, listElement)

Inserts an element into the list at the specified index position.

size(); 

It is used for checking size of list.

clear();

It is used for clearing list.

clone();  

It is used for making a duplicate copy of a list.

contains(listElement)

It returns true if the list contains the specified element.

remove(index) 

It removes the list element stored at the specified index, returning the element that was removed.

sort()

Sorts the items in the list in ascending order.

isEmpty()

Returns true if the list has zero elements.

toString()

Returns the string representation of the list.


Set:
  1. A set is an unordered collection—you can’t access a set element at a specific index. You can only iterate over set elements.
  2. Duplicates are not allowed in set  
Methods available with set are:

add(setElement)

Adds an element to the set if it is not already present.

clear()
Removes all of the elements from the set.

clone()
Makes a duplicate copy of the set.

contains(setElement)
Returns true if the set contains the specified element.

isEmpty()
Returns true if the set has zero elements.

size()
Returns the number of elements in the set (its cardinality).

toString()

Returns the string representation of the set.

Syntax: 
  • Set<id> idList=new Set<id>();   //set of id's
Adding element to set,
idList.add(1);

Removing added element from Set,

idList.remove(1);

Map:

Map is like a collection where each key is paired with a specific value. Each key must be unique, and you can store any type of value, like strings, numbers, or even objects.

Methods available with map are:

keySet(): Returns a set of all the keys in the map.
Example: Set<String> countries = myMap.keySet();

values(): Returns a list of all the values in the map.
Example: List<String> currencies = myMap.values();

get(Key): Retrieves the value associated with the specified key.
Example: String currency = myMap.get('Japan');

put(key, value): Adds or updates a key-value pair in the map.
Example: myMap.put('Germany', 'Euro');

containsKey(key): Checks if the map contains a specified key.
Example: Boolean exists = myMap.containsKey('India');

clear(): Removes all the entries from the map.
Example: myMap.clear();

size(): Returns the number of entries (key-value pairs) in the map.
Example: Integer mapSize = myMap.size();

clone(): Creates a copy of the map.
Example: Map<String, String> clonedMap = myMap.clone();

isEmpty(): Checks if the map is empty (contains no entries).
Example: Boolean isEmpty = myMap.isEmpty();

remove(key): Removes the entry associated with the specified key.
Example: myMap.remove('Japan');


Map in Apex can be used in various ways depending on the type of data you need to store. Below are a few examples showing different types of maps:

Map with String as Key and String as Value:

This is useful when you want to store key-value pairs where both the key and value are strings.

Map<String, String> mapName = new Map<String, String>();
mapName.put('USA', 'Dollar');
mapName.put('India', 'Rupee');

Map with Integer as Key and String as Value:

This is useful when you want to map numeric keys to string values.

Map<Integer, String> mapName = new Map<Integer, String>();
mapName.put(1, 'First');
mapName.put(2, 'Second');

Map with Integer as Key and Object (sObject) as Value:

This is useful when you need to map integers to Salesforce object records (like Account, Contact, etc.).

Map<Integer, Account> mapName = new Map<Integer, Account>();
mapName.put(1, [SELECT Id, Name FROM Account WHERE Name = 'ABC Corp' LIMIT 1]);
mapName.put(2, [SELECT Id, Name FROM Account WHERE Name = 'XYZ Inc' LIMIT 1]);

Map with String as Key and List of sObjects as Value:

This is useful when you need to associate a key (such as a string) with a list of Salesforce object records.

Map<String, List<Account>> mapName = new Map<String, List<Account>>();

// Creating a list of accounts
List<Account> accountList = [SELECT Id, Name FROM Account WHERE Name LIKE 'A%'];
mapName.put('A', accountList);

List<Account> accountListB = [SELECT Id, Name FROM Account WHERE Name LIKE 'B%'];
mapName.put('B', accountListB);


The code provided demonstrates how to store child records (Contacts) related to parent records (Accounts) using a Map. The map associates each account’s ID (parent record) with a list of contacts (child records). This approach is common when working with Salesforce data, especially when you need to manage and display related records in your application.

Here's a detailed explanation of the code:

// Create a Map to store Account IDs as keys and related Contacts as values
Map<String, List<Contact>> accountWithContactsMap = new Map<String, List<Contact>>();

// Create a list to hold Account records
List<Account> accountList = new List<Account>();

// Query Accounts along with their related Contacts (using a nested SOQL query)
accountList = [SELECT Id, Name, (SELECT Id, Name FROM Contacts) FROM Account];

// Iterate through the list of Account records
for (Account obj : accountList) {
    // Check if the Account has any related Contacts
    if (obj.Contacts.size() >= 1) {
        // If the Account ID doesn't already exist as a key in the map
        if (!accountWithContactsMap.containsKey(obj.Id)) {
            // Add the Account's ID and its related Contacts list to the map
            accountWithContactsMap.put(obj.Id, obj.Contacts);
        }
    }
}

2 comments:

  1. Nice article.
    How can we use clone and deepclone for standard datatypes in a Map?

    ReplyDelete