A map is a collection of key-value pairs where each unique key maps to a single value. Keys and values can be any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types.
Example 1:
Map < Integer, String > mapIntString = new Map < Integer, String >();
mapIntString.put( 1, 'One' );
mapIntString.put( 2, 'Two' );
mapIntString.put( 3, 'Three' );
System.debug( 'Value of key 1 is ' + mapIntString.get( 1 ) ); //Will return One
System.debug( 'Whether map containse key 5? ' + mapIntString.containsKey( 5 ) );//Will return false
System.debug( 'Keys are' + mapIntString.keySet() );//Will return 1, 2, 3
System.debug( 'Values are' + mapIntString.values() );//Will return One, Two, Three
Output:
Example 2:
Map<Integer, Account> m = new Map<Integer, Account>();
Map<Integer, Account> m = new Map<Integer, Account>{1=> new Account(name='test')};
Map<Integer, String> m = new Map<Integer, String>{1=>'a',2=>'b'};
m.put(3,'c'); // Assigning values using put()
String str = m.get(2) // returns b
List<Integer> keys = new List<Integer>();
keys = m.keySet(); //Returns the keys from Map
List<String> val = new List<String>();
val = m.values(); //Returns the values from Map
m.containsKey(3); //Returns true if the map contains a mapping for the specified key.
//If the key is a string, the key value is case-sensitive