Core Java

Implement Elvis Operator in Java 8

In Java 8, the Elvis operator (often written as ?: in Groovy and Kotlin) is not available as a built-in feature. However, we can achieve similar functionality using various techniques. Below are multiple methods to simulate the Elvis operator in Java 8+.

1. Understanding the Elvis Operator

The Elvis operator is a shorthand conditional operator found in languages like Groovy and Kotlin. It provides a concise way to handle null values by returning a default value if the original value is null.

For instance, in Kotlin, the following code snippet uses the Elvis operator:

val name = person?.name ?: "Unknown"

This code assigns a value to the name variable. If person is not null and has a name property, that name is assigned. Otherwise, “Unknown” becomes the default value.

2. Implementing the Elvis Operator in Java

2.1 Using Ternary Operator

The ternary operator (?:) is a straightforward way to implement the Elvis operator in Java. It uses a simple conditional expression (value != null) ? value : "default value" to check if value is not null and return it; otherwise, it returns the default value.

ElvisOperatorWithTenaryExample.java

public class ElvisOperatorWithTenaryExample {

    public static String getName(Person person) {
        return person != null ? person.getName() : "Unknown";
    }

    public static void main(String[] args) {
        Person personWithName = new Person();
        personWithName.setName("Alice");
        String name = getName(personWithName);
        System.out.println(name); // Output: Alice

        Person personWithoutName = null;
        String defaultName = getName(personWithoutName);
        System.out.println(defaultName); // Output: Unknown
    }
}

class Person {

    private String name; 

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

2.2 Using Optional Class

Java 8 introduced the Optional class, which offers a more functional approach to handling the presence or absence of a value.

ElvisOperatorWithOptionalClass.java

public class ElvisOperatorWithOptinalClass {

    public static String getName(Person person) {
        return Optional.ofNullable(person)
                .map(Person::getName)
                .orElse("Unknown");
    }

    public static void main(String[] args) {
        Person personWithName = new Person();
        personWithName.setName("Alexander");
        String name = getName(personWithName);
        System.out.println(name); // Output: Alexander

        Person personWithoutName = null;
        String defaultName = getName(personWithoutName);
        System.out.println(defaultName); // Output: Unknown
    }
}

class Person {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

In this example:

  • Optional.ofNullable(person) creates an Optional object that can be null.
  • map(Person::getName) applies the getName method reference to the value inside the Optional (if it exists).
  • orElse("Unknown") returns the default value “Unknown” if the Optional is empty (meaning person was null).

2.3 Using a Custom Method

We can create a custom Elvis method that mimics the Elvis operator’s behaviour.

ElvisOperatorWithCustomMethod.java

public class ElvisOperatorWithCustomMethod {

    public static <T> T elvisOperator(T value, T defaultValue) {
        return (value != null) ? value : defaultValue;
    }

    public static String getName(Person person) {
        return elvisOperator(person.getName(), "UnKnown"); 
    }

    public static void main(String[] args) {

        Person personWithName = new Person();
        personWithName.setName("Alice");
        String result = getName(personWithName);
        System.out.println(result);

        Person personWithoutName = new Person();
        personWithoutName.setName(null);
        String defaultName = getName(personWithoutName);
        System.out.println(defaultName);
    }

}

Explanation:

  • The elvisOperator method is a generic method that takes two arguments: the value to check and the default value.
  • It returns the value if it’s not null, otherwise, it returns the default value.

Output:

Fig 1: Example Output of Elvis Operator Implementation Using Custom Method
Fig 1: Example Output of Elvis Operator Implementation Using Custom Method

2.4 Using Objects.requireNonNullElse() (Java 9+)

The Objects.requireNonNullElse() method can be used to achieve the Elvis operator functionality directly and concisely. The Objects.requireNonNullElse() method handles null values by providing a default value if the given value is null. This method checks if the first argument is null and returns the second argument as the default value if it is.

ElvisOperatorWithObjectsNonNull.java

public class ElvisOperatorWithObjectsNonNull {

    public static void main(String[] args) {
        // Example usage
        Person personWithNullName = new Person(null);
        Person personWithName = new Person("John");

        // Using Objects.requireNonNullElse to provide default name
        String name1 = Objects.requireNonNullElse(personWithNullName.getName(), "Default Name");
        String name2 = Objects.requireNonNullElse(personWithName.getName(), "Default Name");

        System.out.println(name1); // Output: Default Name
        System.out.println(name2); // Output: John
    }
}

3. Conclusion

In this article, we explored various methods to implement the Elvis operator in Java, from using the simple ternary operator to leveraging more advanced techniques such as Optional and utility methods. Each method has its own advantages and can be chosen based on specific requirements and coding style preferences. The ternary operator is straightforward and effective for simple cases, while Optional provides a more functional and declarative approach. Utility methods offer reusability and type safety.

4. Download the Source Code

This was an article on Java 8 Elvis operator implementation.

Download
You can download the full source code of this example here: Java 8 Elvis operator implementation

Omozegie Aziegbe

Omos holds a Master degree in Information Engineering with Network Management from the Robert Gordon University, Aberdeen. Omos is currently a freelance web/application developer who is currently focused on developing Java enterprise applications with the Jakarta EE framework.
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Back to top button