In Java 8 using streams when I chain methods one after the another the execution of operations are performed in pipelined manner.
Example:
List
If you put each function operation into an array, you can iterate over that array with reduce
and pass the last calculated value along in the accumulator until the end of the function array is reached:
var nums = [1,2,3,4,5,6 ];
var fns = [
(x) => {
x = x * x;
console.log('map1=' + x);
return x;
},
(x) => {
x *= 3;
console.log('map2=' + x);
return x;
},
(x) => {
console.log(x);
return x;
}
];
nums.forEach((num) => {
fns.reduce((lastResult, fn) => fn(lastResult), num);
// pass "num" as the initial value for "lastResult",
// before the first function has been called
});
You can't use nums.map
because .map
will necessarily iterate through the whole input array before resolving to the mapped output array (after which the mapped output array will then have another .map
called on it).