Ballerina Collections: Arrays & Maps

Ayesh Almeida
3 min readFeb 22, 2022

--

Photo by Jon Tyson on Unsplash

In programming, a ‘collection’ is simply an object that groups multiple elements into a single unit. Ballerina, offers a set of collections which could use to store any kind of objects.

Arrays

‘Array’ is a sequential data structure consisting of values of the same type. Ballerina Arrays are indexed 0-based. We could use index to access a value in an array.

Arrays are mutable. We could use Langlib function push to insert an value to the end of the array. And it is also possible to update the array using the element index.

The == and != comparison operators are deep. Which means that two arrays are equal if they have the same members in the same order.

You could use a foreach loop to iterate over array elements. If you want to iterate over the array entries along with the respective indexes you could use foreach loop along with Langlib function enumerate .

Ballerina has included set of useful Langlib functions for Array operations. Following are few samples for Langlib function usage. Refer the documentation for more information.

Maps

‘Map’ is an associative structure of multiple string values as keys and their values. map<T> is a mapping between string key and a value of type T . Map syntax is similar to json.

Maps are mutable. We could update map using m[k] = val; syntax, where k is the key for the map entry and val is the value associated with it.

m[k] will return the value which is associated with the key k if the mapping is present or else nil. And we are sure that the mapping for key k is present in the map, we could use Langlib function get to retrieve the value.

The == and != comparison is deep for maps. Two maps are equal if they have the same set of keys and the values for each key are equal.

When we use a foreach loop on a map it will iterate over all the values of the map. If we want to iterate over both values along side keys we will have to use Langlib function entries which would return a map containing [key, value] pair as the value for each key.

Ballerina has included set of useful Langlib functions for Map operations. Following are few samples for Langlib function usage. Refer the documentation for more information.

In this article we have discussed about preliminary collection types available in Ballerina language. In the next article lets discuss about more advance collection types available in Ballerina language.

--

--

Ayesh Almeida
Ayesh Almeida

Written by Ayesh Almeida

A Tech Enthusiast who wants to build simple solutions for complex problems.

Responses (1)