Monday 25 April 2022

How to get first element of map without Iteration using Apex in Salesforce ?

 Use Case : You are receiving a Map with only the size of 1 record. So with out iteration /Loop logic how you will fetch the 1st key and value details ?As Map collection directly don't have the index method.

A Map & Set are an unordered collection of elements so its not allowed to access through index.

Convert the Set into List if required to use the indexed value.

The below code helps to fetch the 1st key and value of the Map with out iteration.

Map<String,String> mapNames = new Map<String,String>();

mapNames.put('1001','XYZ');

//Convert the Map KeySet to List and then apply the index ,Set & Map don't have indexing bec of unordering

System.debug('1st Key Of Map:'+ (new List<String>(mapNames.keySet()))[0]);

System.debug('1st Key Value Of Map:'+ mapNames.get((new List<String>(mapNames.keySet()))[0]));