246. Filter values via Optional.filter()

Using Optional.filter() to accept or reject a wrapped value is a very convenient approach since it can be accomplished without explicitly unwrapping the value. We just pass a predicate (the condition) as an argument and get an Optional object (the initial Optional object if the condition is met or an empty Optional object if the condition is not met).

Let's consider the following uninspired approach for validating the length of a book ISBN:

// Avoid
public boolean validateIsbnLength(Book book) {

Optional<String> isbn = book.getIsbn();

if (isbn.isPresent()) {
return isbn.get().length() > 10;
}

return false;
}

The preceding solution relies on explicitly unwrapping the Optional value. But if we rely on Optional.filter(), we can do it without this explicit unwrapping, as follows:

// Prefer
public boolean validateIsbnLength(Book book) {

Optional<String> isbn = book.getIsbn();

return isbn.filter((i) -> i.length() > 10)
.isPresent();
}
Optional.filter() is also useful for avoiding breaking lambda chains.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.59.192