Java Reference
In-Depth Information
You could also model the invalid value caused by nonconvertible Strings with an empty optional,
so you'd prefer that parseInt could return an optional. You can't change the original Java
method, but nothing prevents you from implementing a tiny utility method, wrapping it, and
returning an optional as desired, as shown in this next listing.
Listing 10.6. Converting a String into an Integer returning an optional
Our suggestion is to collect several methods similar to this in a utility class; let's call it
OptionalUtility. In this way, from now on you'll always be allowed to convert a String into an
Optional<Integer>, using this OptionalUtility.stringToInt method. You can forget that you
encapsulated the ugly try/catch logic in it.
Primitive optionals and why you shouldn't use them
Note that, like streams, optionals also have primitive counterparts—OptionalInt, OptionalLong,
and OptionalDouble—so the method in listing 10.6 could have returned an OptionalInt instead
of Optional<Integer>. In chapter 5 , we encouraged the use of primitive streams, especially when
they could contain a huge number of elements, for performance reasons, but because an
Optional can have at most a single value, that justification doesn't apply here.
We discourage using primitive optionals because they lack the map, flatMap, and filter methods,
which, as you saw in section 10.2 , are the most useful methods of the Optional class. Moreover,
as happens for streams, an optional can't be composed with its primitive counterpart, so, for
example, if the method of listing 10.6 returned OptionalInt, you couldn't pass it as a method
reference to the flatMap method of another optional.
10.4.3. Putting it all together
To demonstrate how the methods of the Optional class presented so far can be used together in
a more compelling use case, suppose you have some Properties that are passed as configuration
arguments to your program. For the purpose of this example and to test the code you'll develop,
create some sample Properties as follows:
 
Search WWH ::




Custom Search