Multiple null checks in Java 8Is Java “pass-by-reference” or “pass-by-value”?How do I efficiently...

Identical projects by students at two different colleges: still plagiarism?

Is there any danger of my neighbor having my wife's signature?

Does the Holy Ark weight 4 tons?

Translation for threshold (figuratively)

Does the Resurrection spell consume material components if the target isn’t willing to be resurrected?

Are there any spells or magic items that allow for making of ‘logic gates or wires’?

Aliased pipeline using head and cut

Are all power cords made equal?

What does an unprocessed RAW file look like?

Ramanujan's radical and how we define an infinite nested radical

Why Third 'Reich'? Why is 'reich' not translated when 'third' is? What is the English synonym of reich?

Exploding Numbers

How to play songs that contain one guitar when we have two or more guitarists?

Why is quixotic not Quixotic (a proper adjective)?

How do I handle a blinded enemy which wants to attack someone it's sure is there?

Why didn't Lorentz conclude that no object can go faster than light?

Reading source code and extracting json from a url

Taking an academic pseudonym?

Empty optional argument or Not giving optional argument at all?

Buying a "Used" Router

Why are `&array` and `array` pointing to the same address?

What does "don't have a baby" imply or mean in this sentence?

Why is Bernie Sanders maximum accepted donation on actblue $5600?

Aligning Systems of Equations



Multiple null checks in Java 8


Is Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?Avoiding != null statementsFastest way to determine if an integer's square root is an integerHow do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?How do I convert a String to an int in Java?Java: checked vs unchecked exception explanationCreating a memory leak with Java













21















I have the below code which is bit ugly for multiple null checks.



String s = null;

if (str1 != null) {
s = str1;
} else if (str2 != null) {
s = str2;
} else if (str3 != null) {
s = str3;
} else {
s = str4;
}


So I tried using Optional.ofNullable like below, but its still difficult to understand if someone reads my code. what is the best approach to do that in Java 8.



String s = Optional.ofNullable(str1)
.orElse(Optional.ofNullable(str2)
.orElse(Optional.ofNullable(str3)
.orElse(str4)));


In Java 9, we can use Optional.ofNullablewith OR, But in Java8 is there any other approach ?










share|improve this question




















  • 3





    Java9 or syntax String s = Optional.ofNullable(str1) .or(() -> Optional.ofNullable(str2)) .or(() -> Optional.ofNullable(str3)) .orElse(str4); looks not as good as the Stream.of I would sya.

    – nullpointer
    11 hours ago











  • Optional.ofNullable is in Java-8 only, i guess.

    – Common Man
    11 hours ago






  • 1





    @OleV.V. Nothing wrong, the OP is already aware of it and is seeking something specific to Java-8.

    – nullpointer
    10 hours ago











  • This was what the elvis operator should do easily. I think it is a good thing it wasn't introduced as it makes it easier to work with null values which I think is the wrong way to go.

    – Thorbjørn Ravn Andersen
    9 hours ago






  • 2





    I know the user is asking for Java-8 specific solution, but on a general note, I would go with StringUtils.firstNonBlank()

    – Mohamed Anees A
    6 hours ago
















21















I have the below code which is bit ugly for multiple null checks.



String s = null;

if (str1 != null) {
s = str1;
} else if (str2 != null) {
s = str2;
} else if (str3 != null) {
s = str3;
} else {
s = str4;
}


So I tried using Optional.ofNullable like below, but its still difficult to understand if someone reads my code. what is the best approach to do that in Java 8.



String s = Optional.ofNullable(str1)
.orElse(Optional.ofNullable(str2)
.orElse(Optional.ofNullable(str3)
.orElse(str4)));


In Java 9, we can use Optional.ofNullablewith OR, But in Java8 is there any other approach ?










share|improve this question




















  • 3





    Java9 or syntax String s = Optional.ofNullable(str1) .or(() -> Optional.ofNullable(str2)) .or(() -> Optional.ofNullable(str3)) .orElse(str4); looks not as good as the Stream.of I would sya.

    – nullpointer
    11 hours ago











  • Optional.ofNullable is in Java-8 only, i guess.

    – Common Man
    11 hours ago






  • 1





    @OleV.V. Nothing wrong, the OP is already aware of it and is seeking something specific to Java-8.

    – nullpointer
    10 hours ago











  • This was what the elvis operator should do easily. I think it is a good thing it wasn't introduced as it makes it easier to work with null values which I think is the wrong way to go.

    – Thorbjørn Ravn Andersen
    9 hours ago






  • 2





    I know the user is asking for Java-8 specific solution, but on a general note, I would go with StringUtils.firstNonBlank()

    – Mohamed Anees A
    6 hours ago














21












21








21


5






I have the below code which is bit ugly for multiple null checks.



String s = null;

if (str1 != null) {
s = str1;
} else if (str2 != null) {
s = str2;
} else if (str3 != null) {
s = str3;
} else {
s = str4;
}


So I tried using Optional.ofNullable like below, but its still difficult to understand if someone reads my code. what is the best approach to do that in Java 8.



String s = Optional.ofNullable(str1)
.orElse(Optional.ofNullable(str2)
.orElse(Optional.ofNullable(str3)
.orElse(str4)));


In Java 9, we can use Optional.ofNullablewith OR, But in Java8 is there any other approach ?










share|improve this question
















I have the below code which is bit ugly for multiple null checks.



String s = null;

if (str1 != null) {
s = str1;
} else if (str2 != null) {
s = str2;
} else if (str3 != null) {
s = str3;
} else {
s = str4;
}


So I tried using Optional.ofNullable like below, but its still difficult to understand if someone reads my code. what is the best approach to do that in Java 8.



String s = Optional.ofNullable(str1)
.orElse(Optional.ofNullable(str2)
.orElse(Optional.ofNullable(str3)
.orElse(str4)));


In Java 9, we can use Optional.ofNullablewith OR, But in Java8 is there any other approach ?







java java-8






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 3 hours ago









Olivier Grégoire

15.3k1663104




15.3k1663104










asked 11 hours ago









sparkersparker

446516




446516








  • 3





    Java9 or syntax String s = Optional.ofNullable(str1) .or(() -> Optional.ofNullable(str2)) .or(() -> Optional.ofNullable(str3)) .orElse(str4); looks not as good as the Stream.of I would sya.

    – nullpointer
    11 hours ago











  • Optional.ofNullable is in Java-8 only, i guess.

    – Common Man
    11 hours ago






  • 1





    @OleV.V. Nothing wrong, the OP is already aware of it and is seeking something specific to Java-8.

    – nullpointer
    10 hours ago











  • This was what the elvis operator should do easily. I think it is a good thing it wasn't introduced as it makes it easier to work with null values which I think is the wrong way to go.

    – Thorbjørn Ravn Andersen
    9 hours ago






  • 2





    I know the user is asking for Java-8 specific solution, but on a general note, I would go with StringUtils.firstNonBlank()

    – Mohamed Anees A
    6 hours ago














  • 3





    Java9 or syntax String s = Optional.ofNullable(str1) .or(() -> Optional.ofNullable(str2)) .or(() -> Optional.ofNullable(str3)) .orElse(str4); looks not as good as the Stream.of I would sya.

    – nullpointer
    11 hours ago











  • Optional.ofNullable is in Java-8 only, i guess.

    – Common Man
    11 hours ago






  • 1





    @OleV.V. Nothing wrong, the OP is already aware of it and is seeking something specific to Java-8.

    – nullpointer
    10 hours ago











  • This was what the elvis operator should do easily. I think it is a good thing it wasn't introduced as it makes it easier to work with null values which I think is the wrong way to go.

    – Thorbjørn Ravn Andersen
    9 hours ago






  • 2





    I know the user is asking for Java-8 specific solution, but on a general note, I would go with StringUtils.firstNonBlank()

    – Mohamed Anees A
    6 hours ago








3




3





Java9 or syntax String s = Optional.ofNullable(str1) .or(() -> Optional.ofNullable(str2)) .or(() -> Optional.ofNullable(str3)) .orElse(str4); looks not as good as the Stream.of I would sya.

– nullpointer
11 hours ago





Java9 or syntax String s = Optional.ofNullable(str1) .or(() -> Optional.ofNullable(str2)) .or(() -> Optional.ofNullable(str3)) .orElse(str4); looks not as good as the Stream.of I would sya.

– nullpointer
11 hours ago













Optional.ofNullable is in Java-8 only, i guess.

– Common Man
11 hours ago





Optional.ofNullable is in Java-8 only, i guess.

– Common Man
11 hours ago




1




1





@OleV.V. Nothing wrong, the OP is already aware of it and is seeking something specific to Java-8.

– nullpointer
10 hours ago





@OleV.V. Nothing wrong, the OP is already aware of it and is seeking something specific to Java-8.

– nullpointer
10 hours ago













This was what the elvis operator should do easily. I think it is a good thing it wasn't introduced as it makes it easier to work with null values which I think is the wrong way to go.

– Thorbjørn Ravn Andersen
9 hours ago





This was what the elvis operator should do easily. I think it is a good thing it wasn't introduced as it makes it easier to work with null values which I think is the wrong way to go.

– Thorbjørn Ravn Andersen
9 hours ago




2




2





I know the user is asking for Java-8 specific solution, but on a general note, I would go with StringUtils.firstNonBlank()

– Mohamed Anees A
6 hours ago





I know the user is asking for Java-8 specific solution, but on a general note, I would go with StringUtils.firstNonBlank()

– Mohamed Anees A
6 hours ago












6 Answers
6






active

oldest

votes


















44














You may do it like so:



String s = Stream.of(str1, str2, str3)
.filter(Objects::nonNull)
.findFirst()
.orElse(str4);





share|improve this answer





















  • 4





    This. Think in what you need, not what you have.

    – Thorbjørn Ravn Andersen
    9 hours ago






  • 5





    How much is the speed overhead? Creating Stream objects, calling 4 methods, creating temporary arrays ({str1, str2, str3}) look like much slower than a local if or ?:, which the Java runtime can optimize. Is there some Stream-specific optimization in javac and the Java runtime which makes it as fast as ?:? If not, I won't recommend this solution in performance-critical code.

    – pts
    8 hours ago








  • 6





    @pts this is very likely to be slower than ?: code and I'm sure you should avoid it in performance-critical code. It's however much more readable and you should recommend it in non-performance-critical code IMO, which I'm sure makes more than 99% of code.

    – Aaron
    7 hours ago






  • 4





    @pts There are no Stream specific optimizations, neither in javac nor in the runtime. This does not preclude the general optimizations, like inlining all of the code, followed by eliminating redundant operations. In principle, the end result could be as efficient as the plain conditional expressions, however, it’s rather unlikely that it ever gets there, as the runtime would spend the necessary effort only on the hottest code paths.

    – Holger
    7 hours ago








  • 7





    Insert mandatory premature optimization comment.

    – Sebastiaan van den Broek
    5 hours ago



















20














How about ternary conditional operator?



String s = str1 != null ? str1 : str2 != null ? str2 : str3 != null ? str3 : str4;





share|improve this answer





















  • 1





    is it java 8 code ?

    – Arun Kumar
    11 hours ago






  • 2





    @ArunKumar I believe you know it isn't.. It works in Java 8 (and prior versions), though.

    – Eran
    11 hours ago








  • 26





    actually, he's looking for "the best approach to do this in Java8". This approach can be used in Java8, so it all just depends on what the OP means by "the best", and on which grounds he bases the decision of what is better on.

    – Stultuske
    11 hours ago






  • 4





    I usually dislike nested ternaries, but this looks pretty clean.

    – JollyJoker
    9 hours ago






  • 1





    This is a huge pain to parse for anyone who isn't reading nested ternary operators every day.

    – Cubic
    2 hours ago





















11














You can also use a loop:



String[] strings = {str1, str2, str3, str4};
for(String str : strings) {
s = str;
if(s != null) break;
}





share|improve this answer































    8














    Current answers are nice but you really should put that in a utility method:



    public static Optional<String> firstNonNull(String... strings) {
    return Arrays.stream(strings)
    .filter(Objects::nonNull)
    .findFirst();
    }


    That method has been in my Util class for years, makes code much cleaner:



    String s = firstNonNull(str1, str2, str3).orElse(str4);


    You can even make it generic:



    public static <T> Optional<T> firstNonNull(T... objects) {
    return Arrays.stream(objects)
    .filter(Objects::nonNull)
    .findFirst();
    }

    // Use
    Student student = firstNonNull(student1, student2, student3).orElseGet(Student::new);





    share|improve this answer


























    • FWIW, in SQL, this function is called coalesce, so i call it that in my code too. Whether that works for you depends how much you like SQL, really.

      – Tom Anderson
      3 hours ago



















    2














    A solution which can be applied to as many element as you want can be :



    Stream.of(str1, str2, str3, str4)
    .filter(Object::nonNull)
    .findFirst()
    .orElseThrow(IllegalArgumentException::new)




    You could imagine a solution like below, but the first one ensures non nullity for all of the elements



    Stream.of(str1, str2, str3).....orElse(str4)





    share|improve this answer



















    • 3





      orElse str4 inspite of it being a null actually

      – nullpointer
      11 hours ago



















    2














    You can also lump up all the Strings into an array of String then do a for loop to check and break from the loop once it's assigned.
    Assuming s1, s2, s3 are all Strings.



    String[] arrayOfStrings = {s1, s2, s3};

    for (String value : arrayOfStrings) {
    if (value != null) {
    s = value;
    break;
    }
    }





    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54800817%2fmultiple-null-checks-in-java-8%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      6 Answers
      6






      active

      oldest

      votes








      6 Answers
      6






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      44














      You may do it like so:



      String s = Stream.of(str1, str2, str3)
      .filter(Objects::nonNull)
      .findFirst()
      .orElse(str4);





      share|improve this answer





















      • 4





        This. Think in what you need, not what you have.

        – Thorbjørn Ravn Andersen
        9 hours ago






      • 5





        How much is the speed overhead? Creating Stream objects, calling 4 methods, creating temporary arrays ({str1, str2, str3}) look like much slower than a local if or ?:, which the Java runtime can optimize. Is there some Stream-specific optimization in javac and the Java runtime which makes it as fast as ?:? If not, I won't recommend this solution in performance-critical code.

        – pts
        8 hours ago








      • 6





        @pts this is very likely to be slower than ?: code and I'm sure you should avoid it in performance-critical code. It's however much more readable and you should recommend it in non-performance-critical code IMO, which I'm sure makes more than 99% of code.

        – Aaron
        7 hours ago






      • 4





        @pts There are no Stream specific optimizations, neither in javac nor in the runtime. This does not preclude the general optimizations, like inlining all of the code, followed by eliminating redundant operations. In principle, the end result could be as efficient as the plain conditional expressions, however, it’s rather unlikely that it ever gets there, as the runtime would spend the necessary effort only on the hottest code paths.

        – Holger
        7 hours ago








      • 7





        Insert mandatory premature optimization comment.

        – Sebastiaan van den Broek
        5 hours ago
















      44














      You may do it like so:



      String s = Stream.of(str1, str2, str3)
      .filter(Objects::nonNull)
      .findFirst()
      .orElse(str4);





      share|improve this answer





















      • 4





        This. Think in what you need, not what you have.

        – Thorbjørn Ravn Andersen
        9 hours ago






      • 5





        How much is the speed overhead? Creating Stream objects, calling 4 methods, creating temporary arrays ({str1, str2, str3}) look like much slower than a local if or ?:, which the Java runtime can optimize. Is there some Stream-specific optimization in javac and the Java runtime which makes it as fast as ?:? If not, I won't recommend this solution in performance-critical code.

        – pts
        8 hours ago








      • 6





        @pts this is very likely to be slower than ?: code and I'm sure you should avoid it in performance-critical code. It's however much more readable and you should recommend it in non-performance-critical code IMO, which I'm sure makes more than 99% of code.

        – Aaron
        7 hours ago






      • 4





        @pts There are no Stream specific optimizations, neither in javac nor in the runtime. This does not preclude the general optimizations, like inlining all of the code, followed by eliminating redundant operations. In principle, the end result could be as efficient as the plain conditional expressions, however, it’s rather unlikely that it ever gets there, as the runtime would spend the necessary effort only on the hottest code paths.

        – Holger
        7 hours ago








      • 7





        Insert mandatory premature optimization comment.

        – Sebastiaan van den Broek
        5 hours ago














      44












      44








      44







      You may do it like so:



      String s = Stream.of(str1, str2, str3)
      .filter(Objects::nonNull)
      .findFirst()
      .orElse(str4);





      share|improve this answer















      You may do it like so:



      String s = Stream.of(str1, str2, str3)
      .filter(Objects::nonNull)
      .findFirst()
      .orElse(str4);






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited 11 hours ago









      nullpointer

      42.5k10101195




      42.5k10101195










      answered 11 hours ago









      Ravindra RanwalaRavindra Ranwala

      9,81231837




      9,81231837








      • 4





        This. Think in what you need, not what you have.

        – Thorbjørn Ravn Andersen
        9 hours ago






      • 5





        How much is the speed overhead? Creating Stream objects, calling 4 methods, creating temporary arrays ({str1, str2, str3}) look like much slower than a local if or ?:, which the Java runtime can optimize. Is there some Stream-specific optimization in javac and the Java runtime which makes it as fast as ?:? If not, I won't recommend this solution in performance-critical code.

        – pts
        8 hours ago








      • 6





        @pts this is very likely to be slower than ?: code and I'm sure you should avoid it in performance-critical code. It's however much more readable and you should recommend it in non-performance-critical code IMO, which I'm sure makes more than 99% of code.

        – Aaron
        7 hours ago






      • 4





        @pts There are no Stream specific optimizations, neither in javac nor in the runtime. This does not preclude the general optimizations, like inlining all of the code, followed by eliminating redundant operations. In principle, the end result could be as efficient as the plain conditional expressions, however, it’s rather unlikely that it ever gets there, as the runtime would spend the necessary effort only on the hottest code paths.

        – Holger
        7 hours ago








      • 7





        Insert mandatory premature optimization comment.

        – Sebastiaan van den Broek
        5 hours ago














      • 4





        This. Think in what you need, not what you have.

        – Thorbjørn Ravn Andersen
        9 hours ago






      • 5





        How much is the speed overhead? Creating Stream objects, calling 4 methods, creating temporary arrays ({str1, str2, str3}) look like much slower than a local if or ?:, which the Java runtime can optimize. Is there some Stream-specific optimization in javac and the Java runtime which makes it as fast as ?:? If not, I won't recommend this solution in performance-critical code.

        – pts
        8 hours ago








      • 6





        @pts this is very likely to be slower than ?: code and I'm sure you should avoid it in performance-critical code. It's however much more readable and you should recommend it in non-performance-critical code IMO, which I'm sure makes more than 99% of code.

        – Aaron
        7 hours ago






      • 4





        @pts There are no Stream specific optimizations, neither in javac nor in the runtime. This does not preclude the general optimizations, like inlining all of the code, followed by eliminating redundant operations. In principle, the end result could be as efficient as the plain conditional expressions, however, it’s rather unlikely that it ever gets there, as the runtime would spend the necessary effort only on the hottest code paths.

        – Holger
        7 hours ago








      • 7





        Insert mandatory premature optimization comment.

        – Sebastiaan van den Broek
        5 hours ago








      4




      4





      This. Think in what you need, not what you have.

      – Thorbjørn Ravn Andersen
      9 hours ago





      This. Think in what you need, not what you have.

      – Thorbjørn Ravn Andersen
      9 hours ago




      5




      5





      How much is the speed overhead? Creating Stream objects, calling 4 methods, creating temporary arrays ({str1, str2, str3}) look like much slower than a local if or ?:, which the Java runtime can optimize. Is there some Stream-specific optimization in javac and the Java runtime which makes it as fast as ?:? If not, I won't recommend this solution in performance-critical code.

      – pts
      8 hours ago







      How much is the speed overhead? Creating Stream objects, calling 4 methods, creating temporary arrays ({str1, str2, str3}) look like much slower than a local if or ?:, which the Java runtime can optimize. Is there some Stream-specific optimization in javac and the Java runtime which makes it as fast as ?:? If not, I won't recommend this solution in performance-critical code.

      – pts
      8 hours ago






      6




      6





      @pts this is very likely to be slower than ?: code and I'm sure you should avoid it in performance-critical code. It's however much more readable and you should recommend it in non-performance-critical code IMO, which I'm sure makes more than 99% of code.

      – Aaron
      7 hours ago





      @pts this is very likely to be slower than ?: code and I'm sure you should avoid it in performance-critical code. It's however much more readable and you should recommend it in non-performance-critical code IMO, which I'm sure makes more than 99% of code.

      – Aaron
      7 hours ago




      4




      4





      @pts There are no Stream specific optimizations, neither in javac nor in the runtime. This does not preclude the general optimizations, like inlining all of the code, followed by eliminating redundant operations. In principle, the end result could be as efficient as the plain conditional expressions, however, it’s rather unlikely that it ever gets there, as the runtime would spend the necessary effort only on the hottest code paths.

      – Holger
      7 hours ago







      @pts There are no Stream specific optimizations, neither in javac nor in the runtime. This does not preclude the general optimizations, like inlining all of the code, followed by eliminating redundant operations. In principle, the end result could be as efficient as the plain conditional expressions, however, it’s rather unlikely that it ever gets there, as the runtime would spend the necessary effort only on the hottest code paths.

      – Holger
      7 hours ago






      7




      7





      Insert mandatory premature optimization comment.

      – Sebastiaan van den Broek
      5 hours ago





      Insert mandatory premature optimization comment.

      – Sebastiaan van den Broek
      5 hours ago













      20














      How about ternary conditional operator?



      String s = str1 != null ? str1 : str2 != null ? str2 : str3 != null ? str3 : str4;





      share|improve this answer





















      • 1





        is it java 8 code ?

        – Arun Kumar
        11 hours ago






      • 2





        @ArunKumar I believe you know it isn't.. It works in Java 8 (and prior versions), though.

        – Eran
        11 hours ago








      • 26





        actually, he's looking for "the best approach to do this in Java8". This approach can be used in Java8, so it all just depends on what the OP means by "the best", and on which grounds he bases the decision of what is better on.

        – Stultuske
        11 hours ago






      • 4





        I usually dislike nested ternaries, but this looks pretty clean.

        – JollyJoker
        9 hours ago






      • 1





        This is a huge pain to parse for anyone who isn't reading nested ternary operators every day.

        – Cubic
        2 hours ago


















      20














      How about ternary conditional operator?



      String s = str1 != null ? str1 : str2 != null ? str2 : str3 != null ? str3 : str4;





      share|improve this answer





















      • 1





        is it java 8 code ?

        – Arun Kumar
        11 hours ago






      • 2





        @ArunKumar I believe you know it isn't.. It works in Java 8 (and prior versions), though.

        – Eran
        11 hours ago








      • 26





        actually, he's looking for "the best approach to do this in Java8". This approach can be used in Java8, so it all just depends on what the OP means by "the best", and on which grounds he bases the decision of what is better on.

        – Stultuske
        11 hours ago






      • 4





        I usually dislike nested ternaries, but this looks pretty clean.

        – JollyJoker
        9 hours ago






      • 1





        This is a huge pain to parse for anyone who isn't reading nested ternary operators every day.

        – Cubic
        2 hours ago
















      20












      20








      20







      How about ternary conditional operator?



      String s = str1 != null ? str1 : str2 != null ? str2 : str3 != null ? str3 : str4;





      share|improve this answer















      How about ternary conditional operator?



      String s = str1 != null ? str1 : str2 != null ? str2 : str3 != null ? str3 : str4;






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited 5 hours ago

























      answered 11 hours ago









      EranEran

      286k37466555




      286k37466555








      • 1





        is it java 8 code ?

        – Arun Kumar
        11 hours ago






      • 2





        @ArunKumar I believe you know it isn't.. It works in Java 8 (and prior versions), though.

        – Eran
        11 hours ago








      • 26





        actually, he's looking for "the best approach to do this in Java8". This approach can be used in Java8, so it all just depends on what the OP means by "the best", and on which grounds he bases the decision of what is better on.

        – Stultuske
        11 hours ago






      • 4





        I usually dislike nested ternaries, but this looks pretty clean.

        – JollyJoker
        9 hours ago






      • 1





        This is a huge pain to parse for anyone who isn't reading nested ternary operators every day.

        – Cubic
        2 hours ago
















      • 1





        is it java 8 code ?

        – Arun Kumar
        11 hours ago






      • 2





        @ArunKumar I believe you know it isn't.. It works in Java 8 (and prior versions), though.

        – Eran
        11 hours ago








      • 26





        actually, he's looking for "the best approach to do this in Java8". This approach can be used in Java8, so it all just depends on what the OP means by "the best", and on which grounds he bases the decision of what is better on.

        – Stultuske
        11 hours ago






      • 4





        I usually dislike nested ternaries, but this looks pretty clean.

        – JollyJoker
        9 hours ago






      • 1





        This is a huge pain to parse for anyone who isn't reading nested ternary operators every day.

        – Cubic
        2 hours ago










      1




      1





      is it java 8 code ?

      – Arun Kumar
      11 hours ago





      is it java 8 code ?

      – Arun Kumar
      11 hours ago




      2




      2





      @ArunKumar I believe you know it isn't.. It works in Java 8 (and prior versions), though.

      – Eran
      11 hours ago







      @ArunKumar I believe you know it isn't.. It works in Java 8 (and prior versions), though.

      – Eran
      11 hours ago






      26




      26





      actually, he's looking for "the best approach to do this in Java8". This approach can be used in Java8, so it all just depends on what the OP means by "the best", and on which grounds he bases the decision of what is better on.

      – Stultuske
      11 hours ago





      actually, he's looking for "the best approach to do this in Java8". This approach can be used in Java8, so it all just depends on what the OP means by "the best", and on which grounds he bases the decision of what is better on.

      – Stultuske
      11 hours ago




      4




      4





      I usually dislike nested ternaries, but this looks pretty clean.

      – JollyJoker
      9 hours ago





      I usually dislike nested ternaries, but this looks pretty clean.

      – JollyJoker
      9 hours ago




      1




      1





      This is a huge pain to parse for anyone who isn't reading nested ternary operators every day.

      – Cubic
      2 hours ago







      This is a huge pain to parse for anyone who isn't reading nested ternary operators every day.

      – Cubic
      2 hours ago













      11














      You can also use a loop:



      String[] strings = {str1, str2, str3, str4};
      for(String str : strings) {
      s = str;
      if(s != null) break;
      }





      share|improve this answer




























        11














        You can also use a loop:



        String[] strings = {str1, str2, str3, str4};
        for(String str : strings) {
        s = str;
        if(s != null) break;
        }





        share|improve this answer


























          11












          11








          11







          You can also use a loop:



          String[] strings = {str1, str2, str3, str4};
          for(String str : strings) {
          s = str;
          if(s != null) break;
          }





          share|improve this answer













          You can also use a loop:



          String[] strings = {str1, str2, str3, str4};
          for(String str : strings) {
          s = str;
          if(s != null) break;
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 11 hours ago









          ernest_kernest_k

          22.7k42547




          22.7k42547























              8














              Current answers are nice but you really should put that in a utility method:



              public static Optional<String> firstNonNull(String... strings) {
              return Arrays.stream(strings)
              .filter(Objects::nonNull)
              .findFirst();
              }


              That method has been in my Util class for years, makes code much cleaner:



              String s = firstNonNull(str1, str2, str3).orElse(str4);


              You can even make it generic:



              public static <T> Optional<T> firstNonNull(T... objects) {
              return Arrays.stream(objects)
              .filter(Objects::nonNull)
              .findFirst();
              }

              // Use
              Student student = firstNonNull(student1, student2, student3).orElseGet(Student::new);





              share|improve this answer


























              • FWIW, in SQL, this function is called coalesce, so i call it that in my code too. Whether that works for you depends how much you like SQL, really.

                – Tom Anderson
                3 hours ago
















              8














              Current answers are nice but you really should put that in a utility method:



              public static Optional<String> firstNonNull(String... strings) {
              return Arrays.stream(strings)
              .filter(Objects::nonNull)
              .findFirst();
              }


              That method has been in my Util class for years, makes code much cleaner:



              String s = firstNonNull(str1, str2, str3).orElse(str4);


              You can even make it generic:



              public static <T> Optional<T> firstNonNull(T... objects) {
              return Arrays.stream(objects)
              .filter(Objects::nonNull)
              .findFirst();
              }

              // Use
              Student student = firstNonNull(student1, student2, student3).orElseGet(Student::new);





              share|improve this answer


























              • FWIW, in SQL, this function is called coalesce, so i call it that in my code too. Whether that works for you depends how much you like SQL, really.

                – Tom Anderson
                3 hours ago














              8












              8








              8







              Current answers are nice but you really should put that in a utility method:



              public static Optional<String> firstNonNull(String... strings) {
              return Arrays.stream(strings)
              .filter(Objects::nonNull)
              .findFirst();
              }


              That method has been in my Util class for years, makes code much cleaner:



              String s = firstNonNull(str1, str2, str3).orElse(str4);


              You can even make it generic:



              public static <T> Optional<T> firstNonNull(T... objects) {
              return Arrays.stream(objects)
              .filter(Objects::nonNull)
              .findFirst();
              }

              // Use
              Student student = firstNonNull(student1, student2, student3).orElseGet(Student::new);





              share|improve this answer















              Current answers are nice but you really should put that in a utility method:



              public static Optional<String> firstNonNull(String... strings) {
              return Arrays.stream(strings)
              .filter(Objects::nonNull)
              .findFirst();
              }


              That method has been in my Util class for years, makes code much cleaner:



              String s = firstNonNull(str1, str2, str3).orElse(str4);


              You can even make it generic:



              public static <T> Optional<T> firstNonNull(T... objects) {
              return Arrays.stream(objects)
              .filter(Objects::nonNull)
              .findFirst();
              }

              // Use
              Student student = firstNonNull(student1, student2, student3).orElseGet(Student::new);






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited 9 hours ago

























              answered 9 hours ago









              walenwalen

              3,73211538




              3,73211538













              • FWIW, in SQL, this function is called coalesce, so i call it that in my code too. Whether that works for you depends how much you like SQL, really.

                – Tom Anderson
                3 hours ago



















              • FWIW, in SQL, this function is called coalesce, so i call it that in my code too. Whether that works for you depends how much you like SQL, really.

                – Tom Anderson
                3 hours ago

















              FWIW, in SQL, this function is called coalesce, so i call it that in my code too. Whether that works for you depends how much you like SQL, really.

              – Tom Anderson
              3 hours ago





              FWIW, in SQL, this function is called coalesce, so i call it that in my code too. Whether that works for you depends how much you like SQL, really.

              – Tom Anderson
              3 hours ago











              2














              A solution which can be applied to as many element as you want can be :



              Stream.of(str1, str2, str3, str4)
              .filter(Object::nonNull)
              .findFirst()
              .orElseThrow(IllegalArgumentException::new)




              You could imagine a solution like below, but the first one ensures non nullity for all of the elements



              Stream.of(str1, str2, str3).....orElse(str4)





              share|improve this answer



















              • 3





                orElse str4 inspite of it being a null actually

                – nullpointer
                11 hours ago
















              2














              A solution which can be applied to as many element as you want can be :



              Stream.of(str1, str2, str3, str4)
              .filter(Object::nonNull)
              .findFirst()
              .orElseThrow(IllegalArgumentException::new)




              You could imagine a solution like below, but the first one ensures non nullity for all of the elements



              Stream.of(str1, str2, str3).....orElse(str4)





              share|improve this answer



















              • 3





                orElse str4 inspite of it being a null actually

                – nullpointer
                11 hours ago














              2












              2








              2







              A solution which can be applied to as many element as you want can be :



              Stream.of(str1, str2, str3, str4)
              .filter(Object::nonNull)
              .findFirst()
              .orElseThrow(IllegalArgumentException::new)




              You could imagine a solution like below, but the first one ensures non nullity for all of the elements



              Stream.of(str1, str2, str3).....orElse(str4)





              share|improve this answer













              A solution which can be applied to as many element as you want can be :



              Stream.of(str1, str2, str3, str4)
              .filter(Object::nonNull)
              .findFirst()
              .orElseThrow(IllegalArgumentException::new)




              You could imagine a solution like below, but the first one ensures non nullity for all of the elements



              Stream.of(str1, str2, str3).....orElse(str4)






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered 11 hours ago









              azroazro

              11.3k41638




              11.3k41638








              • 3





                orElse str4 inspite of it being a null actually

                – nullpointer
                11 hours ago














              • 3





                orElse str4 inspite of it being a null actually

                – nullpointer
                11 hours ago








              3




              3





              orElse str4 inspite of it being a null actually

              – nullpointer
              11 hours ago





              orElse str4 inspite of it being a null actually

              – nullpointer
              11 hours ago











              2














              You can also lump up all the Strings into an array of String then do a for loop to check and break from the loop once it's assigned.
              Assuming s1, s2, s3 are all Strings.



              String[] arrayOfStrings = {s1, s2, s3};

              for (String value : arrayOfStrings) {
              if (value != null) {
              s = value;
              break;
              }
              }





              share|improve this answer




























                2














                You can also lump up all the Strings into an array of String then do a for loop to check and break from the loop once it's assigned.
                Assuming s1, s2, s3 are all Strings.



                String[] arrayOfStrings = {s1, s2, s3};

                for (String value : arrayOfStrings) {
                if (value != null) {
                s = value;
                break;
                }
                }





                share|improve this answer


























                  2












                  2








                  2







                  You can also lump up all the Strings into an array of String then do a for loop to check and break from the loop once it's assigned.
                  Assuming s1, s2, s3 are all Strings.



                  String[] arrayOfStrings = {s1, s2, s3};

                  for (String value : arrayOfStrings) {
                  if (value != null) {
                  s = value;
                  break;
                  }
                  }





                  share|improve this answer













                  You can also lump up all the Strings into an array of String then do a for loop to check and break from the loop once it's assigned.
                  Assuming s1, s2, s3 are all Strings.



                  String[] arrayOfStrings = {s1, s2, s3};

                  for (String value : arrayOfStrings) {
                  if (value != null) {
                  s = value;
                  break;
                  }
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 11 hours ago









                  Daniel ChewDaniel Chew

                  214




                  214






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54800817%2fmultiple-null-checks-in-java-8%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Щит и меч (фильм) Содержание Названия серий | Сюжет |...

                      Венесуэла на летних Олимпийских играх 2000 Содержание Состав...

                      Meter-Bus Содержание Параметры шины | Стандартизация |...