Initialisation of Map:

Map<Integer, String> m = new Map<Integer, String>{5=>’Kalpana’};

m.put(1, ‘Bhavna’);

m.put(2, ‘Sapna’);

m.put(3, ‘Divya’);

m.put(4, ‘Bhavya’);

m.put(2, ‘Divya’); // this will override previous value

Map of List:

Map<Integer, List<Integer>> m = new Map<Integer, List<Integer>>();

m.put(1, new List());

Methods of Map:

put(key,value) Associates the specified value with the specified key in the map. Map<Integer,String> m = new
m.put(1, ‘Bhavna’);m.put(2, ’Sapna’);
putAll(map) Copies all of the mappings from the specified map to the original map. Map<Integer,String> n = new
n.put(3, ’Bhavya’);
n.put(4, ‘Divya’);
System.debug(m);// (1=‘Bhavna’,2=’Sapna’
get(key) Returns the value to which the specified key is mapped, or null if the map contains no value for this key. System.debug(m.get(1)); // ‘Bhavna’
System.debug(m.get(2)); // ’Sapna’
System.debug(m.get(3)); // ’Bhavya’
System.debug(m.get(4)); // ’Divya’
values() Returns a list that contains all the values in the map. List<String> l = new List<String>();
l = m.values();
System.debug(l);// (‘Bhavna’,’Sapna’,’Bhavya’,’Divya’)
clone() Makes a duplicate copy of the map. Map<Integer,String> o = new
o = m.clone();
System.debug(o);// (1=‘Bhavna’,2=’Sapna’
keySet() Returns a set that contains all of the keys in the map. System.debug(m.keySet());
// (1,2,3,4)
containsKey(key) Returns true if the map contains a mapping for the specified key. Boolean result1 = m.containsKey(3);
System.debug(result1); // true
Boolean result2 = m.containsKey(6);
System.debug(result2); // false
isEmpty() Returns true if map has 0 key. Boolean result = m.isEmpty();
System.debug(result); // false
size() Returns the number of key-value pairs in the map. System.debug(m.size()); // 4
remove(key) Removes the mapping for the specified key from the map, if present, and returns the corresponding value. m.remove(4);
clear() Removes all of the key-value mappings from the map. m.clear();

Note: Maps are used frequently to store records that you want to process or as containers for lookup data. It is very common to query for records and store them in a map so that you can do something with them.

Cyntexa CTA

Our Recent Blog

Share This Post