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
sfdcFanBoysfdcFanBoy 

for loop a map

Hey All,

 

I have a map 'm' <String,Decimal> with Values

 

{

 'abc',1000;

 'xyz', 200;

 'abc',100;

 'qwe',600;

 'qwe',800;

}

 

I need to add up the values if the key matches.  So the map should be like below after processing the above map

Abc and qwe are repeating, for them the values should be added. (abc: 1000+100 and qwe: 600+800)

 

{

'abc',1100;

'xyz', 200;

'qwe',1400;

}

 

How to achieve this?

AsitM9AsitM9
map<string,decimal> M= new map<string,decimal>();

//You would like to add a pair
//M.put('abc',10); this should be
if(M.containsKey('abc')){
    Decimal d=M.get('abc')+10;
    M.put('abc',d);
}
else{
    M.put('abc',10);
}

 

sfdcFanBoysfdcFanBoy
Thanks for the reply. Its already in a map<string,decimal>.

But I do not know what Keys it contains, so I cannot use static values like 'abc' directly in this --> if(M.containsKey('abc'))

We have to put a for loop and check for repeating Keys. How?
AsitM9AsitM9
Map never keeps duplicate keys, so no need to check for duplicate.
sfdcFanBoysfdcFanBoy

Ok here's the actual code.

 

String[] xNode = new String[]{};

Decimal[] yNode = new Decimal[]{};

 

//added few strings to xNode - 'abc','xyz','abc','qwe','qwe'

//added few decimals to yNode - 1000,200,100,600,800

 

for(i=0;i<xNode.size();i++){
   m.put(xNode[i],yNode[i]);
}

 

 

Now how do I add the yNodes values if xNode is same. (abc,abc and qwe,qwe)

 

magicforce9magicforce9

Hi,

 

Here is what you are looking for, if you are still looking...

 

String[] xNode = new String[]{'abc','xyz','abc','qwe','qwe'};
Decimal[] yNode = new Decimal[]{1000,200,100,600,800};
Map<String, Decimal> m = new map<String, Decimal>();

for(integer i=0;i<xNode.size();i++){

	if(m.containsKey(xNode[i]))
		m.put(xNode[i], m.get(xNode[i]) + yNode[i]);
	else
		m.put(xNode[i], yNode[i]);
}