Create an Array of Numbers in DataWeave
Learn how to create an array of numbers in DataWeave.
Join the DZone community and get the full member experience.
Join For FreeSometimes we need a simple array to write up/test functionality. In such cases, we create an array, as shown below, and use it.
int[] arr = new int[] {1,2,3,4,5};
But what if we need it in a large size, something like 10,000? In such cases, we create an array with an expected size, and it starts populating data in a simple for/while loop such as below.
int[] arr = new int[10000];
for( int i = 0; i< arr.length; i++ ) {
arr[i] = i+1;
}
The same situation has happened to me in a Transform Message component while I was trying to work on a function that takes an array of numbers as input payload and sends to batch job. To test my batch step performance, I needed a big payload array like 1,000,000. This is how I was able to figure out how to create an array using DataWeave directly. At the same time, I didn't want to go for a Java method just to test my functionality.
A custom recursive function populates the data until the specified max number.
Here is the code for this.
%dw 2.0
output application/json
fun prepareList(list:Array, maxSize: Number) = if(sizeOf(list) >= maxSize )
list
else
prepareList(list ++ [(sizeOf(list) + 1) as Number],maxSize)
---
prepareList([],1000)
The output displayed in Transform Message's preview:
[
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
.
.
.
997,
998,
999,
1000
]
Let me know your thoughts in the comments.
Opinions expressed by DZone contributors are their own.
Comments