Java Reference
In-Depth Information
You could have accomplished the same using the following statement that uses only one filter operation that
includes both predicates for filtering into one predicate:
Person.persons()
.stream()
.filter(p -> p.isMale() && p.getIncome() > 5000.0)
.map(Person::getName)
.forEach(System.out::println);
Ken
Jeff
Applying the Reduce Operation
The reduce operation combines all elements of a stream to produce a single value by applying a combining function
repeatedly. It is also called reduction operation or a fold . Computing the sum, maximum, average, count, etc. of
elements of a stream of integers are examples of the reduce operation. Collecting elements of a stream in a List , Set ,
or Map is also an example of the reduce operation.
The reduce operation takes two parameters called a seed (also called an initial value ) and an accumulator . The
accumulator is a function. If the stream is empty, the seed is the result. Otherwise, the seed represents a partial result.
The partial result and an element are passed to the accumulator, which returns another partial result. This repeats
until all elements are passed to the accumulator. The last value returned from the accumulator is the result of the
reduce operation. Figure 13-10 shows a pictorial view of the reduce operation.
seed
reduce(seed, op)
e1
e2
e3
result
en
Input stream
Figure 13-10. A pictorial view of applying the reduce operation
The stream-related interfaces contain two methods called reduce() and collect() to perform generic reduce
operations. Methods such as sum() , max() , min() , count() , etc. are also available to perform specialized reduce
operations. Note that the specialized methods are not available for all types of streams. For example, having a sum()
method in the Stream<T> interface does not make sense because adding reference type elements, such as adding
two people, is meaningless. So, you will find methods like sum() only in IntStream , LongStream , and DoubleStream
interfaces. Counting the number of elements in a stream makes sense for all types of streams. So, the count() method
is available for all types of streams. I will discuss the reduce() method in this section. I will discuss the collect()
method in several subsequent sections.
 
 
Search WWH ::




Custom Search