ArrayEach
Used to iterate over an array and run the function closure for each item in the array.
This BIF is used to perform an operation on each item in the array, similar to Java's forEach method.
It can also be used to perform operations in parallel if the parallel
argument is set to true.
Parallel Execution
If the parallel
argument is set to true, and no max_threads
are sent, the iterator will be executed in parallel using a ForkJoinPool with parallel streams.
If max_threads
is specified, it will create a new ForkJoinPool with the specified number of threads to run the iterator in parallel, and destroy it after the operation is complete.
Please note that this may not be the most efficient way to iterate, as it will create a new ForkJoinPool for each invocation of the BIF. You may want to consider using a shared ForkJoinPool for better performance.
Method Signature
ArrayEach(array=[array], callback=[function:Consumer], parallel=[boolean], maxThreads=[integer], ordered=[boolean])
Arguments
array
array
true
The array to reduce
callback
function:Consumer
true
The function to invoke for each item. The function will be passed 3 arguments: the value, the index, the array. You can alternatively pass a Java Comparator which will only receive the 1st arg.
parallel
boolean
false
Whether to run the filter in parallel. Defaults to false. If true, the filter will be run in parallel using a ForkJoinPool.
false
maxThreads
integer
false
The maximum number of threads to use when running the filter in parallel. If not passed it will use the default number of threads for the ForkJoinPool. If parallel is false, this argument is ignored.
ordered
boolean
false
(BoxLang only) whether parallel operations should execute and maintain order
false
Examples
Simple Example
letters = [
"a",
"b",
"c",
"d"
];
arrayEach( letters, ( Any element, Any index ) => {
writeOutput( "#index#:#element#;" );
} );
Result: 1:a;2:b;3:c;4:d;
Member Function Example
a = [
"a",
"b",
"c"
];
a.each( ( Any element, Any index, Any array ) => {
writeOutput( "#index#:#element#;" );
} );
Result: 1:a;2:b;3:c;
Additional Examples
aNames = array( "Marcus", "Sarah", "Josefine" );
arrayEach( aNames, ( Any element ) => {
dump( element );
} );
start = getTickCount();
a = [
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i"
];
arrayEach( a, ( Any element, Any index, Any array ) => {
writeOutput( "<code>#index#:#element# [#getTickCount()#]</code><br>" );
sleep( 100 );
}, true, 3 );
writeOutput( "Total Time: #(getTickCount() - start)# milliseconds<br>" );
Related
Last updated
Was this helpful?