How to create a list of lists in Ballerina?

Viewed 318

I need to create a list of lists in Ballerina. In java, I would simply say List<List<String>>. How do I do this in ballerina?

I have the following code.

int[][] arr = [[1,2,3], [4,5,6]];

I need to add elements to the 3rd list and it is not possible as below,

arr[3][0] = 4;
2 Answers

Ballerina has multidimensional arrays, you can do


    int[][] arr = [[1,2,3], [4,5,6]];

You can find more about them here link

In your 2nd sample code you don't have a sub array at index 3. You need to assign a empty array to index 3 and then set it's 0th element to 4.


    arr[3] = [];
    arr[3][0] = 4;
    // or
    arr[3] = [4];

You can create a two dimensional array in Ballerina for this purpose. Arrays in Ballerina are mutable lists of values of dynamic length (link).

The following set of codes helped me to dynamically create a two dimensional array.

//dynamically initializing a 2D array in Ballerina v0.990.2
int[][] iarray = [];
int[] item1 = [];
int[] item2 = [];

item1[0] = 1;
item1[1] = 2;

item2[0] = 1;

iarray[0] = item1;
iarray[2] = item2;

io:println(iarray);

Output : [[1, 2], [], [1]]

Related