Friday, May 26, 2017

Salesforce Collections.

Salesforce Collections 
(List, Set & Map)

List:
→ List is a collection of elements, Such as primitive data types (String, Integer, Date, etc), user defined objects, sObjects, Apex objects or other collections (can be multidimensional up to 5 levels).
→ List allows duplicate values.
→ List index position starts from zero.

Syntax: List<datatype> listName = new List <datatype>();

List Methods:

1. add()
→ Add value in List.
→ Ex.
     List <string> fruits = new List <string>();
     fruits.add('Apple');
     fruits.add('Orange');
     fruits.add('Banana');
     fruits.add('Grape');

OR

List <string> fruits = new List <string>{'Apple','Orange','Banana','Grape'};

2. get()
→ Retrieve a value from the list using Index.
→ Ex.
     String getfruit = fruits.get(1);
          - We get 'Orange' fruit form list using getfruit variable.

3. set()
→ Replace a value with the value at given Index parameter.
→ Ex.
     fruits.set(3,'Strawberry');  
          - In List value has been changed at the index 3. 'Grape' is replace to 'Strawberry'

4. size()
→ Return the number of elements in the List.
→ Ex.
     fruits.size();
          - Give the size of fruits list is 3.

5. clear()
→ Remove the elements from the list.
→ Ex.
     fruits.clear();          

For more List methods.


Set:
→ Set is a collection of unique, unordered elements.
→ It can contain primitive data types (String, Integer, Date, etc) or sObjects.
→ Set allows unique values.

Syntax: Set<datatype> SetName = new Set <datatype>();

Set Methods:

1. add()
→ Adds an element to the set if it is not already present.

2. contains()
→ Returns true if the set contains the specified element.

3. equals()
→ Compares this set with the specified set and returns true if both sets are equal; otherwise, returns false.

4. size()
→ Returns the number of elements in the set.

5. remove()
→ Removes the specified element from the set if it is present. 

For more Set methods


Map:
→ Map is a collection of key-value pair.
→ Keys can be any primitive data types (String, Integer, Date, etc) while values can include primitives, Apex objects, sObjects and other collections.
→ Map allows duplicate values, but each key must be unique.

Syntax: map<datatype,datatype> MapName = new map <datatype,datatype>();

Map Methods:

1. get(key)
→ Returns the value to which the specified key is mapped, or null if the map contains no value for this key.

2. put(key, value)
→ Associates the specified value with the specified key in the map.

3. remove(key)
→ Removes the mapping for the specified key from the map, if present, and returns the corresponding value.

4. size()
→ Returns the number of key-value pairs in the map.

5. values()
→ Returns a list that contains all the values in the map.

For more Map methods




1 comment: