How to properly use Optional to cleanse your Java code of NullPointerExceptions

What’s the problem with null?

Save me! What is Optional and how can we use it?

A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true andget() will return the value.

public Optional<U> map(Function<? super T, ? extends U> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent()) {
return Optional.empty();
} else {
return Optional.ofNullable(mapper.apply(value));
}
}
public Optional<T> filter(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate);
if (!isPresent()) {
return Optional.empty();
} else {
return predicate.test(value) ? this : empty();
}
}
if (obj != null) {
if (obj.getObjTwo() != null) {
obj.getObjTwo().doSomething();
}
}

Closing Thoughts

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store