Java Reference
In-Depth Information
Table 10.1. The methods of the Optional class
Method
Description
empty
Returns an empty Optional instance
filter
If the value is present and matches the given predicate, returns this Optional; otherwise
returns the empty one
flatMap
If a value is present, returns the Optional resulting from the application of the provided
mapping function to it; otherwise returns the empty Optional
get
Returns the value wrapped by this Optional if present; otherwise throws a
NoSuchElementException
ifPresent
If a value is present, invokes the specified consumer with the value; otherwise does nothing
isPresent
Returns true if there is a value present; otherwise false
map
If a value is present, applies the provided mapping function to it
of
Returns an Optional wrapping the given value or throws a NullPointerException if this value
is null
ofNullable
Returns an Optional wrapping the given value or the empty Optional if this value is null
orElse
Returns the value if present or the given default value otherwise
orElseGet
Returns the value if present or the one provided by the given Supplier otherwise
orElseThrow Returns the value if present or throws the exception created by the given Supplier otherwise
10.4. Practical examples of using Optional
As you've learned, effective use of the new Optional class implies a complete rethink of how you
deal with potentially missing values. This rethink involves not only the code you write but,
possibly even more important, how you interact with native Java APIs.
 
Search WWH ::




Custom Search