Maybe I'm overlooking something, but is there a reason that you can't use Optional#map?

The following example prints nothing, as Optional is short-circuiting in the sense that, if the value inside the Optional doesn't exist (it's null or the Optional is empty), it's treated as empty.

Optional.ofNullable("test")
        .map(s -> null)
        .ifPresent(System.out::println);

For that reason, I'd think you could just do the following:

return Optional.ofNullable(thing)
               .map(x -> x.nullableMethod1(a))
               .map(y -> y.nullableMethod2(b))
               .map(Z::nullableMethod3);

This would map your thing if it exists, or return an empty Optional otherwise.

Answer from Jacob G. on Stack Overflow
Top answer
1 of 5
26

Maybe I'm overlooking something, but is there a reason that you can't use Optional#map?

The following example prints nothing, as Optional is short-circuiting in the sense that, if the value inside the Optional doesn't exist (it's null or the Optional is empty), it's treated as empty.

Optional.ofNullable("test")
        .map(s -> null)
        .ifPresent(System.out::println);

For that reason, I'd think you could just do the following:

return Optional.ofNullable(thing)
               .map(x -> x.nullableMethod1(a))
               .map(y -> y.nullableMethod2(b))
               .map(Z::nullableMethod3);

This would map your thing if it exists, or return an empty Optional otherwise.

2 of 5
15

In Java 8, the Elvis operator can be simulated by chaining .map(...) calls on an Optional.ofNullable(...) and capping it with .orElse(...):

Optional.ofNullable(dataObject)
.map(DataObject::getNestedDataObject)
.map(NestedDataObject::getEvenMoreNestedDataObject)
...
.orElse(null);

A full example:

import java.util.Optional;

class Main {
  // Data classes:
  static class Animal {
    Leg leg;

    Animal(Leg leg) {
      this.leg = leg;
    }

    Leg getLeg(){return this.leg;}

    public String toString(){
      String out = "This is an animal";
      out += leg != null ? " with a leg" : "";
      return out;
    }
  }

  static class Leg {
    Toes toes;

    Leg(Toes toes) {
      this.toes = toes;
    }

    Toes getToes(){return this.toes;}

    public String toString(){
      String out = "This is a leg";
      out += toes != null ? " with a collection of toes" : "";
      return out;
    }
  }

  static class Toes {
    Integer numToes;

    Toes(Integer numToes) {
      this.numToes = numToes;
    }

    Integer getNumToes(){return this.numToes;}

    public String toString(){
      String out = "This is a collection of ";
      out += numToes != null && numToes > 0 ? numToes : "no";
      out += " toes";
      return out;
    }
  }

  // A few example Elvis operators:
  static Integer getNumToesOrNull(Animal a) {
    return Optional.ofNullable(a)
      .map(Animal::getLeg)
      .map(Leg::getToes)
      .map(Toes::getNumToes)
      .orElse(null);
  }

  static Toes getToesOrNull(Animal a) {
    return Optional.ofNullable(a)
      .map(Animal::getLeg)
      .map(Leg::getToes)
      .orElse(null);
  }

  static Leg getLegOrNull(Animal a) {
    return Optional.ofNullable(a)
      .map(Animal::getLeg)
      .orElse(null);
  }

  // Main function:
  public static void main(String[] args) {
    // Trying to access 'numToes':
    System.out.println(getNumToesOrNull(new Animal(new Leg(new Toes(4))))); // 4
    System.out.println(getNumToesOrNull(new Animal(new Leg(new Toes(null))))); // null
    System.out.println(getNumToesOrNull(new Animal(new Leg(null)))); // null
    System.out.println(getNumToesOrNull(new Animal(null))); // null
    System.out.println(getNumToesOrNull(null)); // null

    // Trying to access 'toes':
    System.out.println(getToesOrNull(new Animal(new Leg(new Toes(4))))); // This is a collection of 4 toes
    System.out.println(getToesOrNull(new Animal(new Leg(new Toes(null))))); // This is a collection of no toes
    System.out.println(getToesOrNull(new Animal(new Leg(null)))); // null
    System.out.println(getToesOrNull(new Animal(null))); // null
    System.out.println(getToesOrNull(null)); // null

    // Trying to access 'leg':
    System.out.println(getLegOrNull(new Animal(new Leg(new Toes(4))))); // This is a leg with a collection of toes
    System.out.println(getLegOrNull(new Animal(new Leg(new Toes(null))))); // This is a leg with a collection of toes
    System.out.println(getLegOrNull(new Animal(new Leg(null)))); // This is a leg
    System.out.println(getLegOrNull(new Animal(null))); // null
    System.out.println(getLegOrNull(null)); // null
  }
}
🌐
Spring
docs.spring.io › spring-framework › reference › core › expressions › language-ref › operator-elvis.html
The Elvis Operator :: Spring Framework
The Elvis operator (?:) is a shortening of the ternary operator syntax and is used in the Groovy language. With the ternary operator syntax, you often have to repeat a variable twice, as the following Java example shows:
🌐
DZone
dzone.com › coding › java › java 8 elvis operator
Java 8 Elvis Operator
August 28, 2018 - (Note that it is soon to be included in C#, too, and it was proposed for Java SE 7 but didn’t make it into that release.) It works as follows: String version = computer?.getSoundcard()?.getUSB()?.getVersion(); In this case, the variable version will be assigned to null if computer is null, or getSoundcard() returns null, or getUSB() returns null. You don’t need to write complex nested conditions to check for null. In addition, Groovy also includes the Elvis operator “?:” (if you look at it sideways, you’ll recognize Elvis’ famous hair), which can be used for simple cases when a default value is needed.
Top answer
1 of 1
23

Naturally, the best person to ask this question is someone on the JCP Executive Committee, not us. However, that won't prevent me from engaging in some idle speculation.

The answer to every "why wasn't this feature implemented" question is always because the benefits did not exceed the costs.

Eric Lippert (former member of the C# team) says that, in order for a product to have a feature, that feature must be:

  • thought of in the first place
  • desired
  • designed
  • specified
  • implemented
  • tested
  • documented
  • shipped to customers

In other words, there must be many important things that must happen before any new programming language feature can be realized. The costs are larger than you think they are.

On the C# team, every new feature request starts out with a score of minus 100. Then the team evaluates the benefits and the costs, adding points for the benefits, and subtracting points for the costs. If the score doesn't go above zero, the proposed feature is summarily discarded. In other words, the new feature must provide a compelling benefit.

But the Elvis Operator made it into C#. So why didn't it make it into Java?

Despite their apparent similarities, Java and C# have significantly different language philosophies. This is evidenced by the fact that Java enterprise programs tend to be large, structural collections of architecture. Brevity and language expressiveness are sacrificed on the altar of ceremony and ease of coding. Well-known software architectural patterns that everyone on the development team can recognize are preferred over language conveniences.

Consider this Reddit exchange:

The Elvis operator has been proposed for every version of Java since 7, and has been rejected every time. Different languages fall on different points along the spectrum from "pure" to "pragmatic", and languages implementing the Elvis operator do tend to be further toward the pragmatic end of the spectrum than Java.

If you have a team of 15+ year Java pros writing a highly-distributed, highly-concurrent backend processing system of some sort, then you probably want a great degree of architectural rigor.

However, if you have a junior to mid-level team, half of whom migrated from Visual Basic, and you have them writing an ASP.NET web app that mostly just does CRUD operations... then it might be overkill to design a bunch of AbstractFactoryFactory classes to abstract away the fact that you have no control over which columns are nullable in the shitty legacy database that you must use.

These profound differences in language philosophy extend not only to the way the languages are used, but to the way the language design process itself is undertaken. C# is a benevolent dictator language. To get a new feature into C#, you only really have to convince one person: Anders Hejlsberg.

Java takes a more conservative approach. To get a new feature into Java, it must get consensus from a consortium of large vendors such as Oracle, IBM, HP, Fujitsu & Red Hat. Obviously, that process is going to be slower and present a higher bar for new language features.

The question "why wasn't x feature implemented..." always implicitly includes the words, "...if it's obviously such a good idea?" As I have adequately demonstrated here, the choice is never that simple.

🌐
Java Code Geeks
javacodegeeks.com › home › core java
Roll Your Own Pirate-Elvis Operator - Java Code Geeks
March 17, 2015 - So, Java doesn’t have an Elvis operator (or, as it is more formally known, null coalescing operator or null-safe member selection) … While I personally
🌐
Baeldung
baeldung.com › home › java › core java › how to implement elvis operator in java
How to Implement Elvis Operator in Java | Baeldung
May 5, 2024 - In this article, we implemented the Elvis operator in Java 8 using the Optional class and ternary operator. Additionally, we created a custom utility method, elvis(), to handle null checks and default assignments.
🌐
Reddit
reddit.com › r/java › elvis and other null-safe operators in java
Elvis and other null-safe operators in Java : r/java
December 15, 2017 - Let me try your way: Just because you think you can control a large team of engineers of different skill levels to avoid null, doesn't mean the Java language should stop evolving. more reply More replies More replies More replies More replies More replies ... You wouldn’t have to use it. A bunch of us would like to though. Is it needed? Of course not, but neither is ‘var’ and we are getting that sugar. ... The difference is, the elvis operator is philosophically incompatible with what Optional implies about null and proper typing.
🌐
nipafx
nipafx.dev › why-elvis-should-not-visit-java
Why Elvis Should Not Visit Java // nipafx
January 31, 2017 - The desire for the Elvis operator (null-safe member selection) as a killer feature for terse null-handling echoes through the Java community.
Find elsewhere
🌐
Wikipedia
en.wikipedia.org › wiki › Elvis_operator
Elvis operator - Wikipedia
2 weeks ago - The second operand is only evaluated if it is to be returned (short-circuit evaluation). The notation of the Elvis operator was inspired by the ternary conditional operator, ? :, since the Elvis operator expression A ?: B is approximately equivalent to the ternary conditional expression A ?
🌐
Baeldung
baeldung.com › home › java › core java › ternary operator in java
Ternary Operator in Java | Baeldung
September 24, 2025 - The code above demonstrates incorrect usage of the ternary operator because LOGGER.info() is a void method and doesn’t return a value. When using a Java ternary construct, only one of the right-hand side expressions (either expression1 or expression2) is evaluated at runtime.
🌐
Groovy
groovy-lang.org › operators.html
The Apache Groovy programming language - Operators
The ternary operator is a shortcut expression that is equivalent to an if/else branch assigning some value to a variable. ... The "Elvis operator" is a shortening of the ternary operator. One instance of where this is handy is for returning a 'sensible default' value if an expression resolves ...
🌐
nipafx
nipafx.dev › java-pirate-elvis-operator
Roll Your Own Pirate-Elvis Operator // nipafx
March 16, 2015 - Java has no Elvis operator (or null coalescing operator / null-safe member selection) but with lambda expressions / method references you can roll your own.
🌐
Mrhaki
blog.mrhaki.com › 2009 › 08 › groovy-goodness-elvis-operator.html
Groovy Goodness: the Elvis Operator ?: - Messages from mrhaki
November 26, 2010 - Groovy is good at shortening normal Java statements. The Elvis operator is to shorten the ternary operator. If we have a sensible default when the value is null or false (following Groovy truth rules) we can use the Elvis operator.
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Implement Elvis Operator in Java 8 - Java Code Geeks
June 20, 2024 - Learn Java 8 Elvis operator implementation methods: method references, ternary operator, Optional class, and custom methods.
🌐
Jenkov
jenkov.com › tutorials › java › ternary-operator.html
Java Ternary Operator
Notice how the ternary operator conditions checks if the val1 value is larger than or equal to the val2 value. If it is, the ternary operator returns the val1 value. Else it returns the val2 value. The Java ternary operator can also be used to achieve the same effect as the Java Math min() function.
🌐
OpenJDK
mail.openjdk.org › pipermail › coin-dev › 2009-March › 000047.html
Proposal: Elvis and Other Null-Safe Operators
NOTE: The Elvis operator could ... two operators if deemed necessary/desirable (Elvis is generally considered less controversial as far as I can tell). MAJOR ADVANTAGE: It is a common occurance in most large systems to find code that checks for null. Common cases are to provide a default value instead of null, to obtain the result from a nested JavaBean where any ...
🌐
TutorialsPoint
tutorialspoint.com › home › groovy › groovy elvis operator
Groovy Elvis Operator
May 13, 2025 - When left operand is falsey then default value is returned as right operand. Concise Syntax − As elvis operator handles multiple falsey values seemlessly, it reduces the verbosity of the code making it concise and clear.