Java Reference
In-Depth Information
As you might expect, the resulting implementation is quite convoluted and not very readable,
presenting multiple nested conditions coded both as if statements and as a try/catch block. Take
a few minutes to figure out in Quiz 10.3 how you can achieve the same result using what you've
learned in this chapter.
Quiz 10.3: Reading duration from a property using an optional
Using the features of the Optional class and the utility method of listing 10.6 , try to reimplement
the imperative method of listing 10.7 with a single fluent statement.
Answer:
Because the value returned by the Properties.getProperty(String) method is a null when the
required property doesn't exist, it's convenient to turn this value into an optional with the
ofNullable factory method. You can then convert the Optional<String> into an
Optional<Integer>, passing to its flatMap method a reference to the OptionalUtility.stringToInt
method developed in listing 10.6 . Finally, you can easily filter away the negative number. In this
way, if any of these operations will return an empty optional, the method will return the 0 that's
passed as the default value to the orElse method; otherwise, it will return the positive integer
contained in the optional. This is then simply implemented as follows:
public int readDuration(Properties props, String name) {
return Optional.ofNullable(props.getProperty(name))
.flatMap(OptionalUtility::stringToInt)
.filter(i -> i > 0)
.orElse(0);
}
Note the common style in using optionals and streams; both are reminiscent of a database query
where several operations are chained together.
10.5. Summary
In this chapter, you've learned the following:
null references have been historically introduced in programming languages to generally signal the
absence of a value.
Search WWH ::




Custom Search