In this article we will cover three collections in Apex (Lists, Sets, & Maps). Also we will see some examples of them.
- Introduction –
- Collection in any data-type is where we have more than one value stored together for use.
- Collections are useful in triggers as bulkification is needed in triggers. (Need to process in batch of 200 records).
- Collection is also helpful in processing big amount of data.
- Lists –
- A list in Apex is analogous to an array in other programming languages, that it is an ordered list of items that can be referred by their index.
- Declaration of list:
- List<data-type> myList = new List<data-type> ( );
- Adding element to list:
- myList.add(‘Item1’);
- Reading element from list:
- using index. For example: myList[0] will return Item1.
- Using get :
- data-type s = compass.ger(0); [Sets s to be Item1]
- List also stores duplicate data.
- Sets –
- A set is unordered collection of unique items with no duplicates.
- Declaration of Sets:
- Set<String> myStringSet = new Set<String> ( );
- We cannot access element in set using index.
- To check whether elements is present in set or not, we can use Boolean function ( contains ), which will return true if element is present and false if element is not there.
- Maps –
- Maps are collection of key-value pairs, that allows us to store a variety of data-types using a key of any data-type, rather than integer as index.
- Declaration of maps:
- Map<key-type,value-type> mapName = new Map<key-type,value-type> ( );
- The keys within Map must be unique.
- Since key are unique and values can be any, we can use set as a key of map and List as values in following way:
- Map<String,Integer> ageMap = new Map <String,Integer> ( );
- Set<String> names = ageMap.keySet ( );
- List<Integer> ages = ageMap.values ( );
Thank you for reading the article till the end, in next article we will discuss about Operators.
Leave a comment