Hi Divya,
In most cases, lambdas are implemented as a call to a method. The only way to optimize this is to use a method reference, but there is not much to gain in terms of performance.
Java iterators are not functional. They have a state that changes on each call of the
next method, and this method typically returns a different value on each call. This is the opposite of being "functional".
In functional programming, iteration over an evaluated collection (which is something iterators are often used for) is generally abstracted into folds, and folds are typically implemented using recursive calls (recursion for right folds and corecursion for left folds).
Corecursion implementation may be optimized by replacing it with a loop and mutable variables replacing the arguments of the recursive call. With languages having TCE (Tail Call Elimination), this is done by the compiler. There is no such optimization for right folds. In any case, Java does not have TCE. There is, however, the possibility to optimize folds using loops in a library. The library will not have a functional implementation, but it will have a functional interface. For example, a
foldLeft method could be implemented as:
where
head and
tail are methods returning respectively the first element and the list with the first element removed.
As this method is corecursive, it could be optimized manually, or by a compiler using TCE into something like:
(A compiler using TCE does not work exactly like this, but you get the idea.)
On the other hand, Iterators are also used to generate series of data. Instead of looking in a collection for each element to return, the
next method can compute the result. A non functional iterator would compute the result from its mutable state. A functional equivalent (that would not be called an iterator, but rather something like a stateless generator), would compute the next value from the previous one. Sometimes it is just possible like this. If not, the generator
next method returns a pair of the next value and the new generator state.
All these techniques are of course described in detail in my book