Functional alternative to loops

Functional alternative to loops

With new functional features adding up in languages like java, it is good to know how to loop in a functional way. Following are some of functional alternative for ‘for’ loop which you can use

Using Map

The below code looks pretty familiar, right? You see that the for loop is taking each element from the array, performing some operation (here it is multiplying numbers), and putting that into a new array.

Double each element in array:
val numArray = [1,2,3,4,5,6,7,8,9,10];
//Using for loop
var doubleArray = [];
for (var i=0; i < numArray.length; i++){
   doubleArray.push(array[i] * 2)
println(doubleArray); is a builtin function which returns a new array by transforming each element of the source array to a new value based on the supplied method for transformation.

It loops over all the elements in order, calling a supplied transformation function for each element, and internally pushes the results into a new array. We just need to supply the transformation function, and the rest of the work will be done by the map function. For example:

Double each element in array:
val numArray = [1,2,3,4,5,6,7,8,9,10]; 
//Using Map
doubleArray => number*2);

In simple terms, transforms a given array into a new one after performing the transformation function on each element in the array.

Leave a Reply

Your email address will not be published. Required fields are marked *