import ballerina/io;function main (string[] args) {
map m;
map addrMap = {line1:"No. 20", line2:"Palm Grove",
city:"Colombo 03", country:"Sri Lanka"};
io:println(addrMap);
var country = <string>addrMap["country"];
io:println(country);
var city = <string>addrMap.city;
io:println(city);
addrMap["postalCode"] = "00300";
addrMap.postalCode = "00301";
io:println(addrMap);
io:println(addrMap.keys());
io:println(lengthof addrMap);
var isRemoved = addrMap.remove("postalCode");
io:println(addrMap);
}
MapsThe 'map' type is a hash map with keys of type string to values of 'any' type. |
|
import ballerina/io;
|
|
function main (string[] args) {
|
|
map m;
|
Here’s how you create an empty map. |
map addrMap = {line1:"No. 20", line2:"Palm Grove",
city:"Colombo 03", country:"Sri Lanka"};
io:println(addrMap);
|
Here’s how you create a map with initial values. |
var country = <string>addrMap["country"];
io:println(country);
|
You can retrieve a value of a key using an index based notation as follows. |
var city = <string>addrMap.city;
io:println(city);
|
Another way to retrieve a value from a map. |
addrMap["postalCode"] = "00300";
addrMap.postalCode = "00301";
io:println(addrMap);
|
Here’s how you can add or update the value of a key. |
io:println(addrMap.keys());
|
You can use ‘keys’ function in the ‘maps’ package get an array keys. |
io:println(lengthof addrMap);
|
Number of keys in the map. |
var isRemoved = addrMap.remove("postalCode");
io:println(addrMap);
}
|
You can remove a key using the ‘remove’ method. |
$ ballerina run maps.bal
{"line1":"No. 20", "line2":"Palm Grove", "city":"Colombo 03", "country":"Sri Lanka"}
Sri Lanka
Colombo 03
{"line1":"No. 20", "line2":"Palm Grove", "city":"Colombo 03", "country":"Sri Lanka",
"postalCode":"00301"}
["country", "city", "postalCode", "line2", "line1"]
5
{"line1":"No. 20", "line2":"Palm Grove", "city":"Colombo 03", "country":"Sri Lanka"}
|
|