Thursday, 12 September 2013

One step ahead into Lambda

Let’s dig a little deeper into the consequences of modeling an infinite sequence of numbers. Some consequences include the following:

We can’t materialize the whole stream to a Collection, so methods such as collect() won’t be
possible.
We must operate by pulling the elements out of the Stream. We need a bit of code that returns the next element as we need it.

This approach also means that the values of expressions are not computed until they are needed. It might not seem so, but this simple statement actually represents a huge step for Java. Before Java 8, the value of an expression was always computed as soon as it was bound to a variable or passed into a function. This is called eager evaluation and it is, of course, the default behavior for expression evaluation in most mainstream programming languages. With Java 8, a new programming paradigm is being introduced for Java: Stream uses lazy evaluation. This is an extremely powerful new feature, and it takes a bit of getting used to.

Let’s look at a map/filter pipeline,  The stream() method returns a Stream object. The map() and filter() methods (like almost all the operations on Stream) are lazy. At the other end of the pipeline, we have a collect() operation, which materializes the entire Stream back into a Collection. This means that, apart from the materialization back into the Collection, the platform has complete control over how much of the Stream to evaluate, which opens the door to a range of optimizations that are not available in Java 7 and earlier versions. Lazy evaluation requires more care from the programmer, but this burden largely falls upon the library writer. The aim of lambda expressions in Java 8 is to simplify life for the ordinary programmer, even if that requires extra complexity in the platform.

No comments:

Post a Comment