import ballerina/io;public function main (string[] args) {
map words = { a:"ant", b:"bear", c:"cat", d:"dear", e:"elephant" };
io:println("total words count "+ words.count());
string[] animals = words.map(toUpper);
io:println(animals); int[] numbers = [-5, -3, 2, 7, 12];
float avg = numbers.filter((int i) => boolean {
return i >= 0;
})
.average();
io:println("Average of positive numbers " + avg); io:println("\nExecution Order");
json j = {name:"apple", colors:["red", "green"], price:5};
j.map((json j) => string {
string s = j.toString() but {() => ""};
io:println("- map operation's value :" + s);
return s;
})
.foreach((string s) => {
io:println("-- foreach operation's value :" + s);
});}function toUpper (any value) returns string {
var word = <string> value;
match word {
string x => { return x.toUpperCase();}
}
}
Iterable OperationsIterable Operations are a set of built-in operations that can be applied on iterable collections (i.e array, map, json, xml etc) |
|
import ballerina/io;
|
|
public function main (string[] args) {
map words = { a:"ant", b:"bear", c:"cat", d:"dear", e:"elephant" };
|
|
io:println("total words count "+ words.count());
|
Count operation returns the number of elements in any collection type. |
string[] animals = words.map(toUpper);
io:println(animals);
|
Map operation applies given function to each item of the iterable collection and returns a new iterable collection of equal length. The result of the map operation is assigned to a string[] as it returns a collection of a string variable. |
int[] numbers = [-5, -3, 2, 7, 12];
|
|
float avg = numbers.filter((int i) => boolean {
return i >= 0;
})
|
Filter operation returns a collection containing all elements that satisfy the input predicate function. |
.average();
io:println("Average of positive numbers " + avg);
|
Average operation returns the average of the int/float collection. Other support operations are max(), min() and sum(). |
io:println("\nExecution Order");
|
|
json j = {name:"apple", colors:["red", "green"], price:5};
j.map((json j) => string {
string s = j.toString() but {() => ""};
io:println("- map operation's value :" + s);
return s;
})
|
Example of multiple iterable operations. |
.foreach((string s) => {
io:println("-- foreach operation's value :" + s);
});
|
Foreach operation applies the given function to each item of the iterable collection |
}
|
|
function toUpper (any value) returns string {
var word = <string> value;
match word {
string x => { return x.toUpperCase();}
}
}
|
|
$ ballerina run iterable-operations.bal
total words count 5
["ANT", "BEAR", "CAT", "DEAR", "ELEPHANT"]
Average of positive numbers 7.0
|
|
Execution Order
- map operation's value :apple
-- foreach operation's value :apple
- map operation's value :["red","green"]
-- foreach operation's value :["red","green"]
- map operation's value :5
-- foreach operation's value :5
|
|