Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Java 8 Optionals, performing an action if all three are present?

I have some (simplified) code that uses Java Optionals:

Optional<User> maybeTarget = userRepository.findById(id1); Optional<String> maybeSourceName = userRepository.findById(id2).map(User::getName); Optional<String> maybeEventName = eventRepository.findById(id3).map(Event::getName);  maybeTarget.ifPresent(target -> {     maybeSourceName.ifPresent(sourceName -> {         maybeEventName.ifPresent(eventName -> {             sendInvite(target.getEmail(), String.format("Hi %s, $s has invited you to $s", target.getName(), sourceName, meetingName));         }     } } 

Needless to say, this looks and feels bad. But I can't think of another way to do this in a less-nested and more readable way. I considered streaming the 3 Optionals, but discarded the idea as doing a .filter(Optional::isPresent) then a .map(Optional::get) feels even worse.

So is there a better, more 'Java 8' or 'Optional-literate' way of dealing with this situation (essentially multiple Optionals all needed to compute a final operation)?

like image 829
hughjdavey Avatar asked Jan 25 '18 15:01

hughjdavey


People also ask

How do optionals work in Java?

Optional is a container object used to contain not-null objects. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values.

Why do we use optional in Java 8 Give Explanation using a real life example?

Java 8 Optional ExampleOptional can minimize the number of null checks you do in your code by explicitly saying that value can be null and setting proper default values. If you're going to use null, consider the @Nullable annotation.

Why Should Java 8's optional not be used in arguments?

Accepting Optional as parameters causes unnecessary wrapping at caller level.


1 Answers

I think to stream the three Optionals is an overkill, why not the simple

if (maybeTarget.isPresent() && maybeSourceName.isPresent() && maybeEventName.isPresent()) {   ... } 

In my eyes, this states the conditional logic more clearly compared to the use of the stream API.

like image 85
Sharon Ben Asher Avatar answered Sep 22 '22 10:09

Sharon Ben Asher