Use Map Collection In Apex

by Rijwan Mohmmed

Hello friends, today we will discuss Use Map Collection In Apex. In Apex, a Map is a collection of key-value pairs, similar to a JavaScript object or a Python dictionary. Maps are a powerful data structure that can be used to store, retrieve, and manipulate data in a convenient and efficient way. In this blog post, we will be discussing how to use maps collection in Apex and some of the common operations that can be performed on maps.

Also, check this: Modal Popup with Overlay in LWC

Key Highlights :

  1. Maps are a collection of key-value pairs.
  2. Keys are unique.
  3. Values can be duplicated.
  4. To create a new Map, you can use the Map<KeyType, ValueType> constructor.

Code :

For example, the following code creates a new Map that uses strings as the keys and integers as the values:

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

To add key-value pairs to a Map, you can use the put method. For example, the following code adds a key-value pair to the myMap Map:

myMap.put('key1', 1);

To retrieve the value associated with a key, you can use the get method. For example, the following code retrieves the value associated with the ‘key1’ key:

Integer value = myMap.get('key1');

You can also use the containsKey method to check if a key exists in a Map. For example, the following code checks if the ‘key1’ key exists in the myMap Map:

Boolean hasKey = myMap.containsKey('key1');

Additionally, you can use the keyset method to return all the keys in a Map and values method to return all the values in a Map.

Set<String> keys = myMap.keyset();
List<Integer> values = myMap.values();

You can also use the remove method to remove a key-value pair from a Map and the clear method to remove all the key-value pairs from a Map.


You can also use the size method to return the number of key-value pairs in a Map.

Integer size = myMap.size();

Output :

Reference :

  1. Apex Map
What’s your Reaction?

You may also like

Leave a Comment