Java Reference
In-Depth Information
menu.stream()
.filter(Dish::isVegetarian)
.findAny();
The stream pipeline will be optimized behind the scenes to perform a single pass and finish as
soon as a result is found by using short-circuiting. But wait a minute; what's this Optional thing
in the code?
Optional in a nutshell
The Optional<T> class (java.util.Optional) is a container class to represent the existence or
absence of a value. In the previous code, it's possible that findAny doesn't find any element.
Instead of returning null, which is well known for being error prone, the Java 8 library designers
introduced Optional<T>. We won't go into the details of Optional here, because we show in
detail in chapter 10 how your code can benefit from using Optional to avoid bugs related to null
checking. But for now, it's good to know that there are a few methods available in Optional that
force you to explicitly check for the presence of a value or deal with the absence of a value:
isPresent() returns true if Optional contains a value, false otherwise.
ifPresent(Consumer<T> block) executes the given block if a value is present. We introduced the
Consumer functional interface in chapter 3 ; it lets you pass a lambda that takes an argument of type
T and returns void .
Tget() returns the value if present; otherwise it throws a NoSuchElement-Exception .
TorElse(Tother) returns the value if present; otherwise it returns a default value.
For example, in the previous code you'd need to explicitly check for the presence of a dish in the
Optional object to access its name:
5.3.4. Finding the first element
Some streams have an encounter order that specifies the order in which items logically appear
in the stream (for example, a stream generated from a List or from a sorted sequence of data).
For such streams you may wish to find the first element. There's the findFirst method for this,
which works similarly to findAny. For example, the code that follows, given a list of numbers,
finds the first square that's divisible by 3:
 
Search WWH ::




Custom Search