Day 15 - Collections in Apex - Map

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

Collections - Map

===================
Collection of key-value pairs is called a Map

List -> [element1, element2, element3, .......]


Map -> [key1=value1, key2=value2, key3=value2, ....]

Key cannot be repeated. Values can be repeated.

Syntax:

Map<Key_Datatype, Value_Datatype> mapName;

Map<String, String> empMap;


Map<Integer, String> studMap;
Map<String, Double> salaryMap;

Memory Allocation:

Map<Integer, String> studMap = new Map<Integer, String>();

Instance Methods:

1. put(key, value) : To add elements to a Map


---------------------

studMap.put(1001, 'Suresh');
studMap.put(1002, 'Raj');
studMap.put(1005, 'Ramesh');

2. keySet() : It returns all the keys in a map as a set


----------------

Set<Integer> studentRollNos = studMap.keySet();

3. values() : It returns all the values in a map as a list


------------------

List<String> studNames = studMap.values();

4. get(key) : Returns a value for the given key


------------------

Get the name of the student whose Id is 1002

String name = studmap.get(1001);


System.debug('Name = ' + name);

5. containsKey(key) : Returns true if the given key is found


---------------------

Boolean result = studMap.containsKey(1005);


System.debug('Is key found? ' + result);

Collections Comparison
==============================
List Set
Map
----- ----
----

Ordered Elements Unique Elements Key value pairs


Indexed (starts at 0) Not indexed Not indexed
Accepts duplicates Ignore duplicates Key -> Unique

Values -> Can be duplicated


Methods:

add(element) add(element)
put(key, value)
add(index, element) addAll(set2/list2) putAll(map2)
set(index, element) remove(element) keySet()
get(index) contains(element)
values()
remove(index) retainAll()
containsKey(key)
contains(element) isEmpty()
get(key)
isEmpty() size()
isEmpty()
size() clear()
size()
addAll(list2)
clear()
clear()

List<Case> cases = [Select Id, Status, Origin, Reason From Case];


Map<Id, Case> caseMap = new Map<Id, Case>();
for(Case c: cases){
caseMap.put(c.Id, c);
}

Map<Id, Case> caseMap = new Map<Id, Case>([Select CaseNumber, Subject, Status,


Origin, Reason From Case]);

You might also like