Collection Data Types in Salesforce

Collection--

A collection is a group of similar type element. It is the framework that provides Classes and Interfaces for grouping of the similar type elements.

There are three types of collection in Apex--

1. List--
             
A list is the ordered collection of elements which are distinguished by their index. List element can be of any data type(Integer, String, or sObject).

so use list collection whenever you want to identify an element by their index.

List<String> sList = new List<String>();
  sList.add('Jon');
  sList.add('smith');
  system.debug(sList.size());

2. Set--

A set is an unordered collection of elements that don't contain any duplicate element. Set can be any dataType (Integer, String, or sObject).

So use set when you don't want any duplication in your collection.

Set<String> str = new Set<String>();
   str.add('Jane');
   str.add('Jane');
   str.add('Smith');
   system.debug(str); // This prints {Jane, Smith}


3. Map--

A map is the collection of the key-value pair where each key maps a single value.
Key and value can be of any data type (Integer, String, or sObject).

Map<key_data_type,value_data_type> nameOfMap = new Map<Key_dataType, value_data_type>();

map<Integer,String> studentMap = new map<Integer,String>();
   studentMap.put(1,'Jimmy');
   studentMap.put(2,'Jaden');
   studentMap.put(3,'Drek');

   system.debug(ismap.keySet()); // this prints {1,2,3}
   system.debug(isMap.get(2)); // this prints Jaden
   system.debug(isMap.values()); // this prints {Jim,Jaden,Drek}

There are some mapMethod which are used in apex some of them are quite common and others you will rarely use because they are not commonly utilized.


.put(object, object)-- Used to insert an element within a specified key.

.get(key)-- Used to get a value from the map at specified key.

.keySet()-- This method returns a set of a key that is available in the map where it has been used.

.containsKey(key)-- This method returns true if the map contains a value that has been specified within a key.

.remove(key)--  This method remove mapping value at the specified key.

.size()--  This method returns size of map i.e. total element in the map.

.values()--  return a list of values that the map contains.     

.clear()--  Used to clear the map.

.clone()--  Cretaes a duplicate copy of map.

                                             Example

Map<Id,Contact> contactMap = new Map<Id,Contatc>([select id,lastname from contact limit 5]);
for(Id id : contactMap.keySet())
{
       system.debug('LastName is ' + contactMap.get(id).lastname);
}
      

Comments

Popular posts from this blog

Dynamically Add/Delete rows in Visualforce Page

Process Automation Specialist Superbadge

How to show or hide a particular section of Visualforce Page dependent upon picklistfield value