Java Reference
In-Depth Information
a specific object (in this case, the object System.out , which is a static public field of
System ). This is equivalent to the lambda expression:
s -> System . out . println ( s );
This is of course eligible for conversion to an instance of a type that implements
Consumer<? super String> as required by the method signature.
Nothing prevents a map() or filter() call from mutating
elements. It is only a convention that they must not, but it's
one that every Java programmer should adhere to.
There's one final functional technique that we should look at before we move on.
This is the practice of aggregating a collection down to a single value, and it's the
subject of our next section.
Reduce
Let's look at the reduce() method. This implements the reduce idiom, which is
really a family of similar and related operations, some referred to as fold, or aggre‐
gation operations.
In Java 8, reduce() takes two arguments. These are the initial value, which is often
called the identity (or zero), and a function to apply step by step. This function is of
type BinaryOperator<T> , which is another functional interface that takes in two
arguments of the same type, and returns another value of that type. This second
argument to reduce() is a two-argument lambda. reduce() is defined in the java
doc like this:
T reduce ( T identity , BinaryOperator < T > aggregator );
The easy way to think about the second argument to reduce() is that it creates a
“running total” as it runs over the stream. It starts by combining the identity with
the first element of the stream to produce the first result, then combines that result
with the second element of the stream, and so on.
It can help to imagine that the implementation of reduce() works a bit like this:
public T reduce ( T identity , BinaryOperator < T > aggregator ) {
T runningTotal = identity ;
for ( T element : myStream ) {
runningTotal = aggregator . apply ( runningTotal , element );
}
s
a
return result ;
}
 
Search WWH ::




Custom Search