Core Java

Using Java 8 Optionals: Perform Action Only If All Are Present

Java’s Optional class provides a container object which may or may not contain a non-null value. This is useful for avoiding null checks and preventing NullPointerException. Sometimes, we may need to perform an action only if multiple Optional objects contain values. This article will guide us through various ways to achieve this.

1. Example: Combining User Data

For demonstration purposes, Let’s consider a use case where we need to combine data from different sources to create a full user profile. We have three Optional objects: Optional<String> firstName, Optional<String> lastName, and Optional<String> email. We want to perform an action (e.g., create a user profile) only if all of these Optional objects are present.

2. Using isPresent()

One straightforward way is to use isPresent to check each Optional. Here is an example:

import java.util.Optional;

public class IsPresentOptionalExample {

    public static void main(String[] args) {
        Optional<String> firstName = Optional.of("Alice");
        Optional<String> lastName = Optional.of("Doe");
        Optional<String> email = Optional.of("alice.doe@jcg.com");

        if (firstName.isPresent() && lastName.isPresent() && email.isPresent()) {
            String userProfile = createUserProfile(firstName.get(), lastName.get(), email.get());
            System.out.println(userProfile);
        } else {
            System.out.println("One or more required fields are missing");
        }
    }

    private static String createUserProfile(String firstName, String lastName, String email) {
        return "User Profile: " + firstName + " " + lastName + ", Email: " + email;
    }
}

In this example, we check if firstName, lastName, and email are all present. If they are, we create a user profile by calling createUserProfile. Otherwise, we print a message indicating that one or more required fields are missing. This ensures that the action (creating a user profile) is performed only when all necessary data is available.

Output from running the above code is:

User Profile: Alice Doe, Email: alice.doe@jcg.com

3. A Functional Approach with flatMap() and map()

The flatMap method can be used to chain Optional objects in a more functional style. Let’s extend the user profile example to use flatMap for chaining:

public class FlatMapChainingExample {

    public static void main(String[] args) {
        
        Optional<String> firstName = Optional.of("Alice");
        Optional<String> lastName = Optional.of("Doe");
        Optional<String> email = Optional.of("alice.doe@jcg.com");

        firstName.flatMap(fn -> lastName.flatMap(ln -> email.map(em -> createUserProfile(fn, ln, em))))
                 .ifPresentOrElse(
                     System.out::println,
                     () -> System.out.println("One or more required fields are missing")
                 );
    }

    private static String createUserProfile(String firstName, String lastName, String email) {
        return "User Profile: " + firstName + " " + lastName + ", Email: " + email;
    }
}

In this example, flatMap is used to chain the Optional objects. If all Optional objects contain values, createUserProfile is called. If any Optional is empty, a message is printed indicating that the required fields are missing.

4. Using Optional with Streams

Java Streams can be combined with Optional to process sequences of elements. This approach is useful when dealing with a collection of Optional objects. Here’s an example of how to use Streams with Optional:

import java.util.Optional;
import java.util.stream.Stream;

public class OptionalStreamExample {

    public static void main(String[] args) {
        Optional<String> firstName = Optional.of("Alice");
        Optional<String> lastName = Optional.of("Doe");
        Optional<String> email = Optional.of("alice.doe@jcg.com");

        boolean allPresent = Stream.of(firstName, lastName, email)
                                   .allMatch(Optional::isPresent);

        if (allPresent) {
            String userProfile = createUserProfile(
                firstName.get(),
                lastName.get(),
                email.get()
            );
            System.out.println(userProfile);
        } else {
            System.out.println("One or more required fields are missing");
        }
    }

    private static String createUserProfile(String firstName, String lastName, String email) {
        return "User Profile: " + firstName + " " + lastName + ", Email: " + email;
    }
}

In this example, we use allMatch to check if all Optional objects are present. If all are present, we retrieve the values using get() and create the user profile. If any Optional is empty, we print a message indicating that the required fields are missing.

Output:

Fig 1: Output of the Example on Performing Actions When All Optionals Are Available in Java

5. Conclusion

In this article, we explored various methods to perform actions in Java only when all Optional objects are available. Starting with the basic isPresent checks, we moved on to more functional approaches using flatMap for chaining and integrating Optional with Streams. We also demonstrated a practical use case involving user data to illustrate these concepts.

6. Download the Source Code

This article covers how to perform an action in Java only when all Optionals are available.

Download
You can download the full source code of this example here: Java perform action only if all optionals are available

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button