How to update X++ map
Emily Wong
I would like to change value for the key in map. How can I do it? Is it possible?
I have found only method insert(_key,_value) but I don't want to create new key with value, but change the value for the existing key.
2 Answers
How to edit the key
Just remove the old key, then reinsert with the new key.
map = new Map(Types::String,Types::Real)
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
map.remove("b"); // remove key
map.insert("y", 2); // reinsert new key with valueHow to edit the value
Just reinsert the value with insert. The key cannot have duplicates, instead it overwrites.
Return Value
Type: boolean
true if the key did not already exist in the map and has been inserted; otherwise, false.
Remarks
If the key already exists in the map, the value is updated.
For example to manually sum line amount grouping on item group:
Map map = new Map(Types::String,Types::Real);
SalesLine sl;
while select sl where sl.SalesId == "123"
{ map.insert(sl.ItemGroup, sl.LineAmount + (map.exists(sl.ItemGroup) ? map.lookup(sl.ItemGroup) : 0);
}Is equivalent to but performance-wise inferior to:
select sum(LineAmount) sl group ItemGroup where sl.SalesId == "123"; There is no need to remove a key before you insert another value that is to update a key's value. You simply call insert() again.
'insert()' would more accurately be called 'upsert()' in SQL terminology.
Map mymap;
mymap.insert('a',1.0);
mymap.insert('a',1.1);
info(strFmt('%1',mymap.lookup('a'))); // will return '1.1'