Java Reference
In-Depth Information
filter()
We have already met an example of the filter idiom, when we discussed how to
replace an anonymous implementation of FilenameFilter with a lambda. The
filter idiom is used for producing a new subset of a collection, based on some
criteria. Note that in functional programming, it is normal to produce a new
collection, rather than modifying an existing one in-place.
reduce()
The reduce idiom has several different guises. It is an aggregation operation,
which can be called fold or accumulate or aggregate as well as reduce. The basic
idea is to take an initial value, and an aggregation (or reduction) function, and
apply the reduction function to each element in turn, building up a final result
for the whole collection by making a series of intermediate results—similar to a
“running total”—as the reduce operation traverses the collection.
Java has full support for these key functional idioms (and several others). The
implementation is explained in some depth in Chapter 8 , where we discuss Java's
data structures and collections, and in particular the stream abstraction, that makes
all of this possible.
Let's conclude this introduction with some words of caution. It's worth noting that
Java is best regarded as having support for “slightly functional programming.” It is
not an especially functional language, nor does it try to be. Some particular aspects
of Java that mitigate against any claims to being a functional language include the
following:
• Java has no structural types, which means no “true” function types. Every
lambda is automatically converted to the appropriate nominal type.
• Type erasure causes problems for functional programming—type safety can be
lost for higher-order functions.
• Java is inherently mutable (as we'll discuss in Chapter 6 )—mutability is often
regarded as highly undesirable for functional languages.
Despite this, easy access to the basics of functional programing—and especially idi‐
oms such as map, filter, and reduce—is a huge step forward for the Java community.
These idioms are so useful that a large majority of Java developers will never need or
miss the more advanced capabilities provided by languages with a more thorough‐
bred functional pedigree.
Conclusion
By examining Java's type system, we have been able to build up a clear picture of the
worldview that the Java platform has about data types. Java's type system can be
characterized as:
Search WWH ::




Custom Search