Multiple null checks in Java 8












63















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
    Feb 21 at 6:55






  • 1





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

    – nullpointer
    Feb 21 at 8:12






  • 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
    Feb 21 at 12:09






  • 2





    Problem is, Java 8/streams isn't the best solution for this. That code really smells like a refactor is in order but without more context it's really hard to tell. For starters--why aren't three objects that are probably so closely related not already in a collection?

    – Bill K
    Feb 21 at 17:49








  • 1





    @MohamedAneesA would have provided the best answer (as a comment) but didn't specify the source of StringUtils in this case. At any rate, if you HAVE to have these as a bunch of separate strings, coding it as a vargs method like "firstNonBlank" is ideal, the syntax inside will be an array making a simple for-each loop with a return on finding a non-null value trivial and obvious. In this case, java 8 streams are an attractive nuisance. they tempt you to inline and complicate something that should be a simple method/loop.

    – Bill K
    Feb 21 at 17:55


















63















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
    Feb 21 at 6:55






  • 1





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

    – nullpointer
    Feb 21 at 8:12






  • 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
    Feb 21 at 12:09






  • 2





    Problem is, Java 8/streams isn't the best solution for this. That code really smells like a refactor is in order but without more context it's really hard to tell. For starters--why aren't three objects that are probably so closely related not already in a collection?

    – Bill K
    Feb 21 at 17:49








  • 1





    @MohamedAneesA would have provided the best answer (as a comment) but didn't specify the source of StringUtils in this case. At any rate, if you HAVE to have these as a bunch of separate strings, coding it as a vargs method like "firstNonBlank" is ideal, the syntax inside will be an array making a simple for-each loop with a return on finding a non-null value trivial and obvious. In this case, java 8 streams are an attractive nuisance. they tempt you to inline and complicate something that should be a simple method/loop.

    – Bill K
    Feb 21 at 17:55
















63












63








63


12






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 Feb 21 at 15:22









Olivier Grégoire

15.3k1663104




15.3k1663104










asked Feb 21 at 6:45









sparkersparker

651816




651816








  • 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
    Feb 21 at 6:55






  • 1





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

    – nullpointer
    Feb 21 at 8:12






  • 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
    Feb 21 at 12:09






  • 2





    Problem is, Java 8/streams isn't the best solution for this. That code really smells like a refactor is in order but without more context it's really hard to tell. For starters--why aren't three objects that are probably so closely related not already in a collection?

    – Bill K
    Feb 21 at 17:49








  • 1





    @MohamedAneesA would have provided the best answer (as a comment) but didn't specify the source of StringUtils in this case. At any rate, if you HAVE to have these as a bunch of separate strings, coding it as a vargs method like "firstNonBlank" is ideal, the syntax inside will be an array making a simple for-each loop with a return on finding a non-null value trivial and obvious. In this case, java 8 streams are an attractive nuisance. they tempt you to inline and complicate something that should be a simple method/loop.

    – Bill K
    Feb 21 at 17:55
















  • 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
    Feb 21 at 6:55






  • 1





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

    – nullpointer
    Feb 21 at 8:12






  • 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
    Feb 21 at 12:09






  • 2





    Problem is, Java 8/streams isn't the best solution for this. That code really smells like a refactor is in order but without more context it's really hard to tell. For starters--why aren't three objects that are probably so closely related not already in a collection?

    – Bill K
    Feb 21 at 17:49








  • 1





    @MohamedAneesA would have provided the best answer (as a comment) but didn't specify the source of StringUtils in this case. At any rate, if you HAVE to have these as a bunch of separate strings, coding it as a vargs method like "firstNonBlank" is ideal, the syntax inside will be an array making a simple for-each loop with a return on finding a non-null value trivial and obvious. In this case, java 8 streams are an attractive nuisance. they tempt you to inline and complicate something that should be a simple method/loop.

    – Bill K
    Feb 21 at 17:55










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
Feb 21 at 6:55





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
Feb 21 at 6:55




1




1





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

– nullpointer
Feb 21 at 8:12





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

– nullpointer
Feb 21 at 8:12




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
Feb 21 at 12:09





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
Feb 21 at 12:09




2




2





Problem is, Java 8/streams isn't the best solution for this. That code really smells like a refactor is in order but without more context it's really hard to tell. For starters--why aren't three objects that are probably so closely related not already in a collection?

– Bill K
Feb 21 at 17:49







Problem is, Java 8/streams isn't the best solution for this. That code really smells like a refactor is in order but without more context it's really hard to tell. For starters--why aren't three objects that are probably so closely related not already in a collection?

– Bill K
Feb 21 at 17:49






1




1





@MohamedAneesA would have provided the best answer (as a comment) but didn't specify the source of StringUtils in this case. At any rate, if you HAVE to have these as a bunch of separate strings, coding it as a vargs method like "firstNonBlank" is ideal, the syntax inside will be an array making a simple for-each loop with a return on finding a non-null value trivial and obvious. In this case, java 8 streams are an attractive nuisance. they tempt you to inline and complicate something that should be a simple method/loop.

– Bill K
Feb 21 at 17:55







@MohamedAneesA would have provided the best answer (as a comment) but didn't specify the source of StringUtils in this case. At any rate, if you HAVE to have these as a bunch of separate strings, coding it as a vargs method like "firstNonBlank" is ideal, the syntax inside will be an array making a simple for-each loop with a return on finding a non-null value trivial and obvious. In this case, java 8 streams are an attractive nuisance. they tempt you to inline and complicate something that should be a simple method/loop.

– Bill K
Feb 21 at 17:55














7 Answers
7






active

oldest

votes


















125














You may do it like so:



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





share|improve this answer





















  • 13





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

    – Thorbjørn Ravn Andersen
    Feb 21 at 8:23






  • 17





    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
    Feb 21 at 9:58








  • 13





    @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
    Feb 21 at 10:39






  • 34





    Insert mandatory premature optimization comment.

    – Sebastiaan van den Broek
    Feb 21 at 12:31






  • 17





    Great solution! To increase readability a little bit I would suggest to add str4 to the parameters of Stream.of(...) and use orElse(null) in the end.

    – danielp
    Feb 21 at 23:12



















64














How about ternary conditional operator?



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





share|improve this answer





















  • 47





    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
    Feb 21 at 7:13






  • 17





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

    – JollyJoker
    Feb 21 at 8:59






  • 9





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

    – Cubic
    Feb 21 at 15:46








  • 1





    @Cubic: If you think it's hard to parse, write a comment like // take first non-null of str1..3. Once you know what it does, it becomes easy to see how.

    – Peter Cordes
    Feb 22 at 3:36








  • 4





    @Cubic Yet, this is a simple repeated pattern. Once you parsed line 2, you've parsed the entire thing, no matter how many cases are included. And once you are done, you've learned to express a similar selection of ten different cases in a brief, and relatively simple manner. The next time you'll see a ?: ladder, you'll know what it does. (Btw, functional programmers know this as (cond ...) clauses: It's always a guard followed by the appropriate value to use when the guard is true.)

    – cmaster
    Feb 22 at 17:18



















28














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































    20














    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





















    • 8





      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
      Feb 21 at 14:48






    • 4





      If you're going to put it in a utility method you might as well make it efficient.

      – Todd Sewell
      Feb 21 at 19:55











    • @ToddSewell, what do you mean?

      – Gustavo Silva
      Feb 22 at 12:12






    • 4





      @GustavoSilva Todd probably means that, this being a utility method of mine, there's no point in using Arrays.stream() when I can do the same with a for and a != null, which is more efficient. And Todd would be right. However, when I coded this method I was looking for a way of doing this using Java 8 features, just like OP, so there's that.

      – walen
      Feb 22 at 12:23






    • 3





      @GustavoSilva Yeah that's basically it: if you're going to be putting this is a util function concerns about clean code aren't that important anymore, and so you might as well use a faster version.

      – Todd Sewell
      Feb 22 at 17:05





















    11














    I use a helper function, something like



    T firstNonNull<T>(T v0, T... vs) {
    if(v0 != null)
    return v0;
    for(T x : vs) {
    if (x != null)
    return x;
    }
    return null;
    }


    Then this kind of code can be written as



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





    share|improve this answer



















    • 1





      Why the extra v0 parameter?

      – tobias_k
      Feb 23 at 10:08






    • 1





      @tobias_k The extra parameter when using varargs is the idiomatic way in Java to require 1 or more arguments rather than 0 or more. (See item 53 of Effective Java, Ed. 3., which uses min as an example.) I am less convinced that this is appropriate here.

      – Nick
      Feb 23 at 15:49








    • 3





      @Nick Yes, I guessed as much, but the function would work just as well (in fact behave exactly the same) without it.

      – tobias_k
      Feb 23 at 16:54






    • 1





      One of the key reasons for passing an extra first argument is to be explicit about the behaviour when passed an array. In this case, I want firstNonNull(arr) to return arr if it is not null. If it was firstNonNull(T... vs) it would instead return the first non-null entry in arr.

      – Michael Anderson
      Feb 24 at 12:09



















    3














    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



















    • 5





      orElse str4 inspite of it being a null actually

      – nullpointer
      Feb 21 at 6:53











    • @nullpointer Or orElseNull, which amounts to the same if str4 is null.

      – tobias_k
      Feb 23 at 10:09



















    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, s4 are all Strings.



    String arrayOfStrings = {s1, s2, s3};


    s = s4;

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


    Edited to throw in condition for default to s4 if none is assigned.






    share|improve this answer


























    • You have omitted s4 (or str4), which is to supposed be assigned to s in the end, even if it is null.

      – displayName
      Feb 22 at 16:36











    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

























    7 Answers
    7






    active

    oldest

    votes








    7 Answers
    7






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    125














    You may do it like so:



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





    share|improve this answer





















    • 13





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

      – Thorbjørn Ravn Andersen
      Feb 21 at 8:23






    • 17





      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
      Feb 21 at 9:58








    • 13





      @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
      Feb 21 at 10:39






    • 34





      Insert mandatory premature optimization comment.

      – Sebastiaan van den Broek
      Feb 21 at 12:31






    • 17





      Great solution! To increase readability a little bit I would suggest to add str4 to the parameters of Stream.of(...) and use orElse(null) in the end.

      – danielp
      Feb 21 at 23:12
















    125














    You may do it like so:



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





    share|improve this answer





















    • 13





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

      – Thorbjørn Ravn Andersen
      Feb 21 at 8:23






    • 17





      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
      Feb 21 at 9:58








    • 13





      @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
      Feb 21 at 10:39






    • 34





      Insert mandatory premature optimization comment.

      – Sebastiaan van den Broek
      Feb 21 at 12:31






    • 17





      Great solution! To increase readability a little bit I would suggest to add str4 to the parameters of Stream.of(...) and use orElse(null) in the end.

      – danielp
      Feb 21 at 23:12














    125












    125








    125







    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 Feb 22 at 8:57









    Sulthan

    97.4k16158202




    97.4k16158202










    answered Feb 21 at 6:51









    Ravindra RanwalaRavindra Ranwala

    10.6k42040




    10.6k42040








    • 13





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

      – Thorbjørn Ravn Andersen
      Feb 21 at 8:23






    • 17





      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
      Feb 21 at 9:58








    • 13





      @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
      Feb 21 at 10:39






    • 34





      Insert mandatory premature optimization comment.

      – Sebastiaan van den Broek
      Feb 21 at 12:31






    • 17





      Great solution! To increase readability a little bit I would suggest to add str4 to the parameters of Stream.of(...) and use orElse(null) in the end.

      – danielp
      Feb 21 at 23:12














    • 13





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

      – Thorbjørn Ravn Andersen
      Feb 21 at 8:23






    • 17





      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
      Feb 21 at 9:58








    • 13





      @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
      Feb 21 at 10:39






    • 34





      Insert mandatory premature optimization comment.

      – Sebastiaan van den Broek
      Feb 21 at 12:31






    • 17





      Great solution! To increase readability a little bit I would suggest to add str4 to the parameters of Stream.of(...) and use orElse(null) in the end.

      – danielp
      Feb 21 at 23:12








    13




    13





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

    – Thorbjørn Ravn Andersen
    Feb 21 at 8:23





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

    – Thorbjørn Ravn Andersen
    Feb 21 at 8:23




    17




    17





    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
    Feb 21 at 9:58







    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
    Feb 21 at 9:58






    13




    13





    @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
    Feb 21 at 10:39





    @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
    Feb 21 at 10:39




    34




    34





    Insert mandatory premature optimization comment.

    – Sebastiaan van den Broek
    Feb 21 at 12:31





    Insert mandatory premature optimization comment.

    – Sebastiaan van den Broek
    Feb 21 at 12:31




    17




    17





    Great solution! To increase readability a little bit I would suggest to add str4 to the parameters of Stream.of(...) and use orElse(null) in the end.

    – danielp
    Feb 21 at 23:12





    Great solution! To increase readability a little bit I would suggest to add str4 to the parameters of Stream.of(...) and use orElse(null) in the end.

    – danielp
    Feb 21 at 23:12













    64














    How about ternary conditional operator?



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





    share|improve this answer





















    • 47





      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
      Feb 21 at 7:13






    • 17





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

      – JollyJoker
      Feb 21 at 8:59






    • 9





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

      – Cubic
      Feb 21 at 15:46








    • 1





      @Cubic: If you think it's hard to parse, write a comment like // take first non-null of str1..3. Once you know what it does, it becomes easy to see how.

      – Peter Cordes
      Feb 22 at 3:36








    • 4





      @Cubic Yet, this is a simple repeated pattern. Once you parsed line 2, you've parsed the entire thing, no matter how many cases are included. And once you are done, you've learned to express a similar selection of ten different cases in a brief, and relatively simple manner. The next time you'll see a ?: ladder, you'll know what it does. (Btw, functional programmers know this as (cond ...) clauses: It's always a guard followed by the appropriate value to use when the guard is true.)

      – cmaster
      Feb 22 at 17:18
















    64














    How about ternary conditional operator?



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





    share|improve this answer





















    • 47





      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
      Feb 21 at 7:13






    • 17





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

      – JollyJoker
      Feb 21 at 8:59






    • 9





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

      – Cubic
      Feb 21 at 15:46








    • 1





      @Cubic: If you think it's hard to parse, write a comment like // take first non-null of str1..3. Once you know what it does, it becomes easy to see how.

      – Peter Cordes
      Feb 22 at 3:36








    • 4





      @Cubic Yet, this is a simple repeated pattern. Once you parsed line 2, you've parsed the entire thing, no matter how many cases are included. And once you are done, you've learned to express a similar selection of ten different cases in a brief, and relatively simple manner. The next time you'll see a ?: ladder, you'll know what it does. (Btw, functional programmers know this as (cond ...) clauses: It's always a guard followed by the appropriate value to use when the guard is true.)

      – cmaster
      Feb 22 at 17:18














    64












    64








    64







    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 Feb 21 at 19:42









    candied_orange

    4,3221648




    4,3221648










    answered Feb 21 at 6:48









    EranEran

    287k37467556




    287k37467556








    • 47





      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
      Feb 21 at 7:13






    • 17





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

      – JollyJoker
      Feb 21 at 8:59






    • 9





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

      – Cubic
      Feb 21 at 15:46








    • 1





      @Cubic: If you think it's hard to parse, write a comment like // take first non-null of str1..3. Once you know what it does, it becomes easy to see how.

      – Peter Cordes
      Feb 22 at 3:36








    • 4





      @Cubic Yet, this is a simple repeated pattern. Once you parsed line 2, you've parsed the entire thing, no matter how many cases are included. And once you are done, you've learned to express a similar selection of ten different cases in a brief, and relatively simple manner. The next time you'll see a ?: ladder, you'll know what it does. (Btw, functional programmers know this as (cond ...) clauses: It's always a guard followed by the appropriate value to use when the guard is true.)

      – cmaster
      Feb 22 at 17:18














    • 47





      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
      Feb 21 at 7:13






    • 17





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

      – JollyJoker
      Feb 21 at 8:59






    • 9





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

      – Cubic
      Feb 21 at 15:46








    • 1





      @Cubic: If you think it's hard to parse, write a comment like // take first non-null of str1..3. Once you know what it does, it becomes easy to see how.

      – Peter Cordes
      Feb 22 at 3:36








    • 4





      @Cubic Yet, this is a simple repeated pattern. Once you parsed line 2, you've parsed the entire thing, no matter how many cases are included. And once you are done, you've learned to express a similar selection of ten different cases in a brief, and relatively simple manner. The next time you'll see a ?: ladder, you'll know what it does. (Btw, functional programmers know this as (cond ...) clauses: It's always a guard followed by the appropriate value to use when the guard is true.)

      – cmaster
      Feb 22 at 17:18








    47




    47





    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
    Feb 21 at 7:13





    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
    Feb 21 at 7:13




    17




    17





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

    – JollyJoker
    Feb 21 at 8:59





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

    – JollyJoker
    Feb 21 at 8:59




    9




    9





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

    – Cubic
    Feb 21 at 15:46







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

    – Cubic
    Feb 21 at 15:46






    1




    1





    @Cubic: If you think it's hard to parse, write a comment like // take first non-null of str1..3. Once you know what it does, it becomes easy to see how.

    – Peter Cordes
    Feb 22 at 3:36







    @Cubic: If you think it's hard to parse, write a comment like // take first non-null of str1..3. Once you know what it does, it becomes easy to see how.

    – Peter Cordes
    Feb 22 at 3:36






    4




    4





    @Cubic Yet, this is a simple repeated pattern. Once you parsed line 2, you've parsed the entire thing, no matter how many cases are included. And once you are done, you've learned to express a similar selection of ten different cases in a brief, and relatively simple manner. The next time you'll see a ?: ladder, you'll know what it does. (Btw, functional programmers know this as (cond ...) clauses: It's always a guard followed by the appropriate value to use when the guard is true.)

    – cmaster
    Feb 22 at 17:18





    @Cubic Yet, this is a simple repeated pattern. Once you parsed line 2, you've parsed the entire thing, no matter how many cases are included. And once you are done, you've learned to express a similar selection of ten different cases in a brief, and relatively simple manner. The next time you'll see a ?: ladder, you'll know what it does. (Btw, functional programmers know this as (cond ...) clauses: It's always a guard followed by the appropriate value to use when the guard is true.)

    – cmaster
    Feb 22 at 17:18











    28














    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




























      28














      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


























        28












        28








        28







        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 Feb 21 at 6:52









        ernest_kernest_k

        23.1k42647




        23.1k42647























            20














            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





















            • 8





              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
              Feb 21 at 14:48






            • 4





              If you're going to put it in a utility method you might as well make it efficient.

              – Todd Sewell
              Feb 21 at 19:55











            • @ToddSewell, what do you mean?

              – Gustavo Silva
              Feb 22 at 12:12






            • 4





              @GustavoSilva Todd probably means that, this being a utility method of mine, there's no point in using Arrays.stream() when I can do the same with a for and a != null, which is more efficient. And Todd would be right. However, when I coded this method I was looking for a way of doing this using Java 8 features, just like OP, so there's that.

              – walen
              Feb 22 at 12:23






            • 3





              @GustavoSilva Yeah that's basically it: if you're going to be putting this is a util function concerns about clean code aren't that important anymore, and so you might as well use a faster version.

              – Todd Sewell
              Feb 22 at 17:05


















            20














            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





















            • 8





              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
              Feb 21 at 14:48






            • 4





              If you're going to put it in a utility method you might as well make it efficient.

              – Todd Sewell
              Feb 21 at 19:55











            • @ToddSewell, what do you mean?

              – Gustavo Silva
              Feb 22 at 12:12






            • 4





              @GustavoSilva Todd probably means that, this being a utility method of mine, there's no point in using Arrays.stream() when I can do the same with a for and a != null, which is more efficient. And Todd would be right. However, when I coded this method I was looking for a way of doing this using Java 8 features, just like OP, so there's that.

              – walen
              Feb 22 at 12:23






            • 3





              @GustavoSilva Yeah that's basically it: if you're going to be putting this is a util function concerns about clean code aren't that important anymore, and so you might as well use a faster version.

              – Todd Sewell
              Feb 22 at 17:05
















            20












            20








            20







            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 Feb 21 at 9:10

























            answered Feb 21 at 8:51









            walenwalen

            3,87211539




            3,87211539








            • 8





              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
              Feb 21 at 14:48






            • 4





              If you're going to put it in a utility method you might as well make it efficient.

              – Todd Sewell
              Feb 21 at 19:55











            • @ToddSewell, what do you mean?

              – Gustavo Silva
              Feb 22 at 12:12






            • 4





              @GustavoSilva Todd probably means that, this being a utility method of mine, there's no point in using Arrays.stream() when I can do the same with a for and a != null, which is more efficient. And Todd would be right. However, when I coded this method I was looking for a way of doing this using Java 8 features, just like OP, so there's that.

              – walen
              Feb 22 at 12:23






            • 3





              @GustavoSilva Yeah that's basically it: if you're going to be putting this is a util function concerns about clean code aren't that important anymore, and so you might as well use a faster version.

              – Todd Sewell
              Feb 22 at 17:05
















            • 8





              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
              Feb 21 at 14:48






            • 4





              If you're going to put it in a utility method you might as well make it efficient.

              – Todd Sewell
              Feb 21 at 19:55











            • @ToddSewell, what do you mean?

              – Gustavo Silva
              Feb 22 at 12:12






            • 4





              @GustavoSilva Todd probably means that, this being a utility method of mine, there's no point in using Arrays.stream() when I can do the same with a for and a != null, which is more efficient. And Todd would be right. However, when I coded this method I was looking for a way of doing this using Java 8 features, just like OP, so there's that.

              – walen
              Feb 22 at 12:23






            • 3





              @GustavoSilva Yeah that's basically it: if you're going to be putting this is a util function concerns about clean code aren't that important anymore, and so you might as well use a faster version.

              – Todd Sewell
              Feb 22 at 17:05










            8




            8





            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
            Feb 21 at 14:48





            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
            Feb 21 at 14:48




            4




            4





            If you're going to put it in a utility method you might as well make it efficient.

            – Todd Sewell
            Feb 21 at 19:55





            If you're going to put it in a utility method you might as well make it efficient.

            – Todd Sewell
            Feb 21 at 19:55













            @ToddSewell, what do you mean?

            – Gustavo Silva
            Feb 22 at 12:12





            @ToddSewell, what do you mean?

            – Gustavo Silva
            Feb 22 at 12:12




            4




            4





            @GustavoSilva Todd probably means that, this being a utility method of mine, there's no point in using Arrays.stream() when I can do the same with a for and a != null, which is more efficient. And Todd would be right. However, when I coded this method I was looking for a way of doing this using Java 8 features, just like OP, so there's that.

            – walen
            Feb 22 at 12:23





            @GustavoSilva Todd probably means that, this being a utility method of mine, there's no point in using Arrays.stream() when I can do the same with a for and a != null, which is more efficient. And Todd would be right. However, when I coded this method I was looking for a way of doing this using Java 8 features, just like OP, so there's that.

            – walen
            Feb 22 at 12:23




            3




            3





            @GustavoSilva Yeah that's basically it: if you're going to be putting this is a util function concerns about clean code aren't that important anymore, and so you might as well use a faster version.

            – Todd Sewell
            Feb 22 at 17:05







            @GustavoSilva Yeah that's basically it: if you're going to be putting this is a util function concerns about clean code aren't that important anymore, and so you might as well use a faster version.

            – Todd Sewell
            Feb 22 at 17:05













            11














            I use a helper function, something like



            T firstNonNull<T>(T v0, T... vs) {
            if(v0 != null)
            return v0;
            for(T x : vs) {
            if (x != null)
            return x;
            }
            return null;
            }


            Then this kind of code can be written as



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





            share|improve this answer



















            • 1





              Why the extra v0 parameter?

              – tobias_k
              Feb 23 at 10:08






            • 1





              @tobias_k The extra parameter when using varargs is the idiomatic way in Java to require 1 or more arguments rather than 0 or more. (See item 53 of Effective Java, Ed. 3., which uses min as an example.) I am less convinced that this is appropriate here.

              – Nick
              Feb 23 at 15:49








            • 3





              @Nick Yes, I guessed as much, but the function would work just as well (in fact behave exactly the same) without it.

              – tobias_k
              Feb 23 at 16:54






            • 1





              One of the key reasons for passing an extra first argument is to be explicit about the behaviour when passed an array. In this case, I want firstNonNull(arr) to return arr if it is not null. If it was firstNonNull(T... vs) it would instead return the first non-null entry in arr.

              – Michael Anderson
              Feb 24 at 12:09
















            11














            I use a helper function, something like



            T firstNonNull<T>(T v0, T... vs) {
            if(v0 != null)
            return v0;
            for(T x : vs) {
            if (x != null)
            return x;
            }
            return null;
            }


            Then this kind of code can be written as



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





            share|improve this answer



















            • 1





              Why the extra v0 parameter?

              – tobias_k
              Feb 23 at 10:08






            • 1





              @tobias_k The extra parameter when using varargs is the idiomatic way in Java to require 1 or more arguments rather than 0 or more. (See item 53 of Effective Java, Ed. 3., which uses min as an example.) I am less convinced that this is appropriate here.

              – Nick
              Feb 23 at 15:49








            • 3





              @Nick Yes, I guessed as much, but the function would work just as well (in fact behave exactly the same) without it.

              – tobias_k
              Feb 23 at 16:54






            • 1





              One of the key reasons for passing an extra first argument is to be explicit about the behaviour when passed an array. In this case, I want firstNonNull(arr) to return arr if it is not null. If it was firstNonNull(T... vs) it would instead return the first non-null entry in arr.

              – Michael Anderson
              Feb 24 at 12:09














            11












            11








            11







            I use a helper function, something like



            T firstNonNull<T>(T v0, T... vs) {
            if(v0 != null)
            return v0;
            for(T x : vs) {
            if (x != null)
            return x;
            }
            return null;
            }


            Then this kind of code can be written as



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





            share|improve this answer













            I use a helper function, something like



            T firstNonNull<T>(T v0, T... vs) {
            if(v0 != null)
            return v0;
            for(T x : vs) {
            if (x != null)
            return x;
            }
            return null;
            }


            Then this kind of code can be written as



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






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Feb 22 at 1:36









            Michael AndersonMichael Anderson

            45.9k696149




            45.9k696149








            • 1





              Why the extra v0 parameter?

              – tobias_k
              Feb 23 at 10:08






            • 1





              @tobias_k The extra parameter when using varargs is the idiomatic way in Java to require 1 or more arguments rather than 0 or more. (See item 53 of Effective Java, Ed. 3., which uses min as an example.) I am less convinced that this is appropriate here.

              – Nick
              Feb 23 at 15:49








            • 3





              @Nick Yes, I guessed as much, but the function would work just as well (in fact behave exactly the same) without it.

              – tobias_k
              Feb 23 at 16:54






            • 1





              One of the key reasons for passing an extra first argument is to be explicit about the behaviour when passed an array. In this case, I want firstNonNull(arr) to return arr if it is not null. If it was firstNonNull(T... vs) it would instead return the first non-null entry in arr.

              – Michael Anderson
              Feb 24 at 12:09














            • 1





              Why the extra v0 parameter?

              – tobias_k
              Feb 23 at 10:08






            • 1





              @tobias_k The extra parameter when using varargs is the idiomatic way in Java to require 1 or more arguments rather than 0 or more. (See item 53 of Effective Java, Ed. 3., which uses min as an example.) I am less convinced that this is appropriate here.

              – Nick
              Feb 23 at 15:49








            • 3





              @Nick Yes, I guessed as much, but the function would work just as well (in fact behave exactly the same) without it.

              – tobias_k
              Feb 23 at 16:54






            • 1





              One of the key reasons for passing an extra first argument is to be explicit about the behaviour when passed an array. In this case, I want firstNonNull(arr) to return arr if it is not null. If it was firstNonNull(T... vs) it would instead return the first non-null entry in arr.

              – Michael Anderson
              Feb 24 at 12:09








            1




            1





            Why the extra v0 parameter?

            – tobias_k
            Feb 23 at 10:08





            Why the extra v0 parameter?

            – tobias_k
            Feb 23 at 10:08




            1




            1





            @tobias_k The extra parameter when using varargs is the idiomatic way in Java to require 1 or more arguments rather than 0 or more. (See item 53 of Effective Java, Ed. 3., which uses min as an example.) I am less convinced that this is appropriate here.

            – Nick
            Feb 23 at 15:49







            @tobias_k The extra parameter when using varargs is the idiomatic way in Java to require 1 or more arguments rather than 0 or more. (See item 53 of Effective Java, Ed. 3., which uses min as an example.) I am less convinced that this is appropriate here.

            – Nick
            Feb 23 at 15:49






            3




            3





            @Nick Yes, I guessed as much, but the function would work just as well (in fact behave exactly the same) without it.

            – tobias_k
            Feb 23 at 16:54





            @Nick Yes, I guessed as much, but the function would work just as well (in fact behave exactly the same) without it.

            – tobias_k
            Feb 23 at 16:54




            1




            1





            One of the key reasons for passing an extra first argument is to be explicit about the behaviour when passed an array. In this case, I want firstNonNull(arr) to return arr if it is not null. If it was firstNonNull(T... vs) it would instead return the first non-null entry in arr.

            – Michael Anderson
            Feb 24 at 12:09





            One of the key reasons for passing an extra first argument is to be explicit about the behaviour when passed an array. In this case, I want firstNonNull(arr) to return arr if it is not null. If it was firstNonNull(T... vs) it would instead return the first non-null entry in arr.

            – Michael Anderson
            Feb 24 at 12:09











            3














            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



















            • 5





              orElse str4 inspite of it being a null actually

              – nullpointer
              Feb 21 at 6:53











            • @nullpointer Or orElseNull, which amounts to the same if str4 is null.

              – tobias_k
              Feb 23 at 10:09
















            3














            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



















            • 5





              orElse str4 inspite of it being a null actually

              – nullpointer
              Feb 21 at 6:53











            • @nullpointer Or orElseNull, which amounts to the same if str4 is null.

              – tobias_k
              Feb 23 at 10:09














            3












            3








            3







            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 Feb 21 at 6:52









            azroazro

            11.3k41638




            11.3k41638








            • 5





              orElse str4 inspite of it being a null actually

              – nullpointer
              Feb 21 at 6:53











            • @nullpointer Or orElseNull, which amounts to the same if str4 is null.

              – tobias_k
              Feb 23 at 10:09














            • 5





              orElse str4 inspite of it being a null actually

              – nullpointer
              Feb 21 at 6:53











            • @nullpointer Or orElseNull, which amounts to the same if str4 is null.

              – tobias_k
              Feb 23 at 10:09








            5




            5





            orElse str4 inspite of it being a null actually

            – nullpointer
            Feb 21 at 6:53





            orElse str4 inspite of it being a null actually

            – nullpointer
            Feb 21 at 6:53













            @nullpointer Or orElseNull, which amounts to the same if str4 is null.

            – tobias_k
            Feb 23 at 10:09





            @nullpointer Or orElseNull, which amounts to the same if str4 is null.

            – tobias_k
            Feb 23 at 10:09











            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, s4 are all Strings.



            String arrayOfStrings = {s1, s2, s3};


            s = s4;

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


            Edited to throw in condition for default to s4 if none is assigned.






            share|improve this answer


























            • You have omitted s4 (or str4), which is to supposed be assigned to s in the end, even if it is null.

              – displayName
              Feb 22 at 16:36
















            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, s4 are all Strings.



            String arrayOfStrings = {s1, s2, s3};


            s = s4;

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


            Edited to throw in condition for default to s4 if none is assigned.






            share|improve this answer


























            • You have omitted s4 (or str4), which is to supposed be assigned to s in the end, even if it is null.

              – displayName
              Feb 22 at 16:36














            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, s4 are all Strings.



            String arrayOfStrings = {s1, s2, s3};


            s = s4;

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


            Edited to throw in condition for default to s4 if none is assigned.






            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, s4 are all Strings.



            String arrayOfStrings = {s1, s2, s3};


            s = s4;

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


            Edited to throw in condition for default to s4 if none is assigned.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Feb 23 at 18:20

























            answered Feb 21 at 7:00









            Daniel ChewDaniel Chew

            415




            415













            • You have omitted s4 (or str4), which is to supposed be assigned to s in the end, even if it is null.

              – displayName
              Feb 22 at 16:36



















            • You have omitted s4 (or str4), which is to supposed be assigned to s in the end, even if it is null.

              – displayName
              Feb 22 at 16:36

















            You have omitted s4 (or str4), which is to supposed be assigned to s in the end, even if it is null.

            – displayName
            Feb 22 at 16:36





            You have omitted s4 (or str4), which is to supposed be assigned to s in the end, even if it is null.

            – displayName
            Feb 22 at 16:36


















            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

            How to send String Array data to Server using php in android

            Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

            Is anime1.com a legal site for watching anime?