function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sadik Shaiksadik Shaik 

Get values for same keyset and club them into a list for each key

I have a list of maps like ({DK=1, EC=3, JH=5, NT=3, PK=2}, {DK=1, EC=24, JH=31, NT=66, PK=1}). if you look at here both maps having same keys, i want to club the values of same key into an array for eacy key some thing like this ({DK=[1,1]},{EC=[3,24]},{JH=[5,31]}). How can i acheive this, thanks in advance.
Abdul KhatriAbdul Khatri
Here is the code
Map<String,Integer> map1 = new Map<String, Integer>{'DK'=>1, 'EC'=>3, 'JH'=>5, 'NT'=>3, 'PK'=>2};
Map<String,Integer> map2 = new Map<String, Integer> {'DK'=>1, 'EC'=>24, 'JH'=>31, 'NT'=>66, 'PK'=>1};
List<Map<String, Integer>> listMap = new List<Map<String, Integer>>{map1, map2};
system.debug(listMap);
Map<String, List<Integer>> resultMap = new Map<String, List<Integer>>();

for(Integer i = 0 ; i < listMap.size() ; i++) {

	Map<String,Integer> tempMap = listMap.get(i); 
    for(String str : tempMap.keySet()) {
        
        if (resultMap.containskey(str)) {
            List<Integer> tempList = resultMap.get(str);
            tempList.add(tempMap.get(str));
            resultMap.put(str, tempList);
        }else{
            resultMap.put(str,new List<Integer>{tempMap.get(str)});
        }
    }
}
system.debug('resultMap : ' + resultMap);

 
Abdul KhatriAbdul Khatri
Was it helpful?
Abdul KhatriAbdul Khatri
Hello are you following up?