Java Reference
In-Depth Information
NOTE
There are other methods on
Stream
and its primitive specialized variants. Specifically,
range
and
iterate
give us other ways of generating our own streams.
Optional
Something I've glossed over so far is that
reduce
can come in a couple of forms: the one
we've seen, which takes an initial value, and another variant, which doesn't. When the initial
value is left out, the first call to the reducer uses the first two elements of the
Stream
. This is
useful if there's no sensible initial value for a
reduce
operation and will return an instance of
Optional
.
Optional
is a new core library data type that is designed to provide a better alternative to
null
. There's quite a lot of hatred for the old
null
value. Even the man who invented the
concept, Tony Hoare, described it as “my billion-dollar mistake.” That's the trouble with be-
ing an influential computer scientist—you can make a billion-dollar mistake without even
seeing the billion dollars yourself!
null
is often used to represent the absence of a value, and this is the use case that
Optional
is replacing. The problem with using
null
in order to represent absence is the dreaded
NullPointerException
. If you refer to a variable that is
null
, your code blows up. The
goal of
Optional
is twofold. First, it encourages the coder to make appropriate checks as to
whether a variable is
null
in order to avoid bugs. Second, it documents values that are ex-
pected to be absent in a class's API. This makes it easier to see where the bodies are buried.
Let's take a look at the API for
Optional
in order to get a feel for how to use it. If you want
to create an
Optional
instance from a value, there is a factory method called
of
. The
Op-
tional
is now a container for this value, which can be pulled out with
get
, as shown in
Example 4-22. Creating an Optional from a value
Optional
<
String
>
a
=
Optional
.
of
(
"a"
);
assertEquals
(
"a"
,
a
.
get
());
Because an
Optional
may also represent an absent value, there's also a factory method
called
empty
, and you can convert a nullable value into an
Optional
using the
ofNullable