multiple null checks in Java8Avoiding != null statementsFastest way to determine if an integer's square root...
Found a major flaw in paper from home university – to which I would like to return
How to scroll to next div using Javascript?
Build ASCII Podiums
Stream.findFirst different than Optional.of?
Why is the meaning of kanji 閑 "leisure"?
Integral check. Is partial fractions the only way?
Last Reboot commands don't agree
Is layered encryption more secure than long passwords?
Buying a "Used" Router
Face Value of SOFR futures
How to achieve physical gender equality?
Rudeness by being polite
How can changes in personality/values of a person who turned into a vampire be explained?
How to read the error when writing vector files in QGIS 3.0
Is opening a file faster than reading variable content?
Define function that behaves almost identically to Mathematica function
How can guns be countered by melee combat without raw-ability or exceptional explanations?
How to play songs that contain one guitar when we have two or more guitarists?
What does "don't have a baby" imply or mean in this sentence?
How do I add a strong "onion flavor" to the biryani (in restaurant style)?
How do I write a maintainable, fast, compile-time bit-mask in C++?
Why is Shelob considered evil?
How do I handle a blinded enemy which wants to attack someone it's sure is there?
Sing Baby Shark
multiple null checks in Java8
Avoiding != null statementsFastest way to determine if an integer's square root is an integerIs null check needed before calling instanceof?Java: checked vs unchecked exception explanationString comparisions in javaNaming multiple strings with an incremented countString.intern() how to workJava8 Optional fire one method if null , another if not null Best ApproachHow to search specific string form list in multithreaded environment.?Object with complex data structure cloning/splitting in Java 6
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.ofNullable
with OR
, But in Java8 is there any other approach ?
java java-8
add a comment |
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.ofNullable
with OR
, But in Java8 is there any other approach ?
java java-8
3
Java9or
syntaxString s = Optional.ofNullable(str1) .or(() -> Optional.ofNullable(str2)) .or(() -> Optional.ofNullable(str3)) .orElse(str4);
looks not as good as theStream.of
I would sya.
– nullpointer
5 hours ago
Optional.ofNullable
is in Java-8 only, i guess.
– Common Man
5 hours ago
1
@OleV.V. Nothing wrong, the OP is already aware of it and is seeking something specific to Java-8.
– nullpointer
4 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
3 hours ago
I know the user is asking for Java-8 specific solution, but on a general note, I would go withStringUtils.firstNonBlank()
– Mohamed Anees A
12 mins ago
add a comment |
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.ofNullable
with OR
, But in Java8 is there any other approach ?
java java-8
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.ofNullable
with OR
, But in Java8 is there any other approach ?
java java-8
java java-8
edited 5 hours ago
azro
11.2k41638
11.2k41638
asked 5 hours ago
sparkersparker
423515
423515
3
Java9or
syntaxString s = Optional.ofNullable(str1) .or(() -> Optional.ofNullable(str2)) .or(() -> Optional.ofNullable(str3)) .orElse(str4);
looks not as good as theStream.of
I would sya.
– nullpointer
5 hours ago
Optional.ofNullable
is in Java-8 only, i guess.
– Common Man
5 hours ago
1
@OleV.V. Nothing wrong, the OP is already aware of it and is seeking something specific to Java-8.
– nullpointer
4 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
3 hours ago
I know the user is asking for Java-8 specific solution, but on a general note, I would go withStringUtils.firstNonBlank()
– Mohamed Anees A
12 mins ago
add a comment |
3
Java9or
syntaxString s = Optional.ofNullable(str1) .or(() -> Optional.ofNullable(str2)) .or(() -> Optional.ofNullable(str3)) .orElse(str4);
looks not as good as theStream.of
I would sya.
– nullpointer
5 hours ago
Optional.ofNullable
is in Java-8 only, i guess.
– Common Man
5 hours ago
1
@OleV.V. Nothing wrong, the OP is already aware of it and is seeking something specific to Java-8.
– nullpointer
4 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
3 hours ago
I know the user is asking for Java-8 specific solution, but on a general note, I would go withStringUtils.firstNonBlank()
– Mohamed Anees A
12 mins 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
5 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
5 hours ago
Optional.ofNullable
is in Java-8 only, i guess.– Common Man
5 hours ago
Optional.ofNullable
is in Java-8 only, i guess.– Common Man
5 hours ago
1
1
@OleV.V. Nothing wrong, the OP is already aware of it and is seeking something specific to Java-8.
– nullpointer
4 hours ago
@OleV.V. Nothing wrong, the OP is already aware of it and is seeking something specific to Java-8.
– nullpointer
4 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
3 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
3 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
12 mins 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
12 mins ago
add a comment |
6 Answers
6
active
oldest
votes
You may do it like so:
String s = Stream.of(str1, str2, str3)
.filter(Objects::nonNull)
.findFirst()
.orElse(str4);
2
This. Think in what you need, not what you have.
– Thorbjørn Ravn Andersen
3 hours ago
1
How much is the speed overhead? Creating Stream objects, calling 4 methods, creating temporary arrays ({str1, str2, str3}
) look like much slower than a localif
or?:
, which the Java runtime can optimize. Is there some Stream-specific optimization injavac
and the Java runtime which makes it as fast as?:
? If not, I won't recommend this solution in performance-critical code.
– pts
2 hours ago
1
@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
1 hour ago
1
@pts There are no Stream specific optimizations, neither injavac
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
1 hour ago
add a comment |
How about ternary conditional operator?
String s = str1 != null ? str1 : str2 != null ? str2 : str3 != null ? str3 : str4;
1
is it java 8 code ?
– Arun Kumar
5 hours ago
1
@ArunKumar I believe you know it isn't.. It works in Java 8 (and prior versions), though.
– Eran
5 hours ago
in question solution already posted for <8 ...user is asking for java 8..
– Arun Kumar
5 hours ago
11
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
5 hours ago
I usually dislike nested ternaries, but this looks pretty clean.
– JollyJoker
3 hours ago
add a comment |
You can also use a loop:
String[] strings = {str1, str2, str3, str4};
for(String str : strings) {
s = str;
if(s != null) break;
}
add a comment |
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)
1
orElsestr4
inspite of it being a null actually
– nullpointer
5 hours ago
add a comment |
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);
add a comment |
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;
}
}
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54800817%2fmultiple-null-checks-in-java8%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
You may do it like so:
String s = Stream.of(str1, str2, str3)
.filter(Objects::nonNull)
.findFirst()
.orElse(str4);
2
This. Think in what you need, not what you have.
– Thorbjørn Ravn Andersen
3 hours ago
1
How much is the speed overhead? Creating Stream objects, calling 4 methods, creating temporary arrays ({str1, str2, str3}
) look like much slower than a localif
or?:
, which the Java runtime can optimize. Is there some Stream-specific optimization injavac
and the Java runtime which makes it as fast as?:
? If not, I won't recommend this solution in performance-critical code.
– pts
2 hours ago
1
@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
1 hour ago
1
@pts There are no Stream specific optimizations, neither injavac
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
1 hour ago
add a comment |
You may do it like so:
String s = Stream.of(str1, str2, str3)
.filter(Objects::nonNull)
.findFirst()
.orElse(str4);
2
This. Think in what you need, not what you have.
– Thorbjørn Ravn Andersen
3 hours ago
1
How much is the speed overhead? Creating Stream objects, calling 4 methods, creating temporary arrays ({str1, str2, str3}
) look like much slower than a localif
or?:
, which the Java runtime can optimize. Is there some Stream-specific optimization injavac
and the Java runtime which makes it as fast as?:
? If not, I won't recommend this solution in performance-critical code.
– pts
2 hours ago
1
@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
1 hour ago
1
@pts There are no Stream specific optimizations, neither injavac
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
1 hour ago
add a comment |
You may do it like so:
String s = Stream.of(str1, str2, str3)
.filter(Objects::nonNull)
.findFirst()
.orElse(str4);
You may do it like so:
String s = Stream.of(str1, str2, str3)
.filter(Objects::nonNull)
.findFirst()
.orElse(str4);
edited 5 hours ago
nullpointer
42.5k10101195
42.5k10101195
answered 5 hours ago
Ravindra RanwalaRavindra Ranwala
9,81231737
9,81231737
2
This. Think in what you need, not what you have.
– Thorbjørn Ravn Andersen
3 hours ago
1
How much is the speed overhead? Creating Stream objects, calling 4 methods, creating temporary arrays ({str1, str2, str3}
) look like much slower than a localif
or?:
, which the Java runtime can optimize. Is there some Stream-specific optimization injavac
and the Java runtime which makes it as fast as?:
? If not, I won't recommend this solution in performance-critical code.
– pts
2 hours ago
1
@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
1 hour ago
1
@pts There are no Stream specific optimizations, neither injavac
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
1 hour ago
add a comment |
2
This. Think in what you need, not what you have.
– Thorbjørn Ravn Andersen
3 hours ago
1
How much is the speed overhead? Creating Stream objects, calling 4 methods, creating temporary arrays ({str1, str2, str3}
) look like much slower than a localif
or?:
, which the Java runtime can optimize. Is there some Stream-specific optimization injavac
and the Java runtime which makes it as fast as?:
? If not, I won't recommend this solution in performance-critical code.
– pts
2 hours ago
1
@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
1 hour ago
1
@pts There are no Stream specific optimizations, neither injavac
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
1 hour ago
2
2
This. Think in what you need, not what you have.
– Thorbjørn Ravn Andersen
3 hours ago
This. Think in what you need, not what you have.
– Thorbjørn Ravn Andersen
3 hours ago
1
1
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
2 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
2 hours ago
1
1
@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
1 hour 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
1 hour ago
1
1
@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
1 hour 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
1 hour ago
add a comment |
How about ternary conditional operator?
String s = str1 != null ? str1 : str2 != null ? str2 : str3 != null ? str3 : str4;
1
is it java 8 code ?
– Arun Kumar
5 hours ago
1
@ArunKumar I believe you know it isn't.. It works in Java 8 (and prior versions), though.
– Eran
5 hours ago
in question solution already posted for <8 ...user is asking for java 8..
– Arun Kumar
5 hours ago
11
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
5 hours ago
I usually dislike nested ternaries, but this looks pretty clean.
– JollyJoker
3 hours ago
add a comment |
How about ternary conditional operator?
String s = str1 != null ? str1 : str2 != null ? str2 : str3 != null ? str3 : str4;
1
is it java 8 code ?
– Arun Kumar
5 hours ago
1
@ArunKumar I believe you know it isn't.. It works in Java 8 (and prior versions), though.
– Eran
5 hours ago
in question solution already posted for <8 ...user is asking for java 8..
– Arun Kumar
5 hours ago
11
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
5 hours ago
I usually dislike nested ternaries, but this looks pretty clean.
– JollyJoker
3 hours ago
add a comment |
How about ternary conditional operator?
String s = str1 != null ? str1 : str2 != null ? str2 : str3 != null ? str3 : str4;
How about ternary conditional operator?
String s = str1 != null ? str1 : str2 != null ? str2 : str3 != null ? str3 : str4;
answered 5 hours ago
EranEran
286k37466554
286k37466554
1
is it java 8 code ?
– Arun Kumar
5 hours ago
1
@ArunKumar I believe you know it isn't.. It works in Java 8 (and prior versions), though.
– Eran
5 hours ago
in question solution already posted for <8 ...user is asking for java 8..
– Arun Kumar
5 hours ago
11
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
5 hours ago
I usually dislike nested ternaries, but this looks pretty clean.
– JollyJoker
3 hours ago
add a comment |
1
is it java 8 code ?
– Arun Kumar
5 hours ago
1
@ArunKumar I believe you know it isn't.. It works in Java 8 (and prior versions), though.
– Eran
5 hours ago
in question solution already posted for <8 ...user is asking for java 8..
– Arun Kumar
5 hours ago
11
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
5 hours ago
I usually dislike nested ternaries, but this looks pretty clean.
– JollyJoker
3 hours ago
1
1
is it java 8 code ?
– Arun Kumar
5 hours ago
is it java 8 code ?
– Arun Kumar
5 hours ago
1
1
@ArunKumar I believe you know it isn't.. It works in Java 8 (and prior versions), though.
– Eran
5 hours ago
@ArunKumar I believe you know it isn't.. It works in Java 8 (and prior versions), though.
– Eran
5 hours ago
in question solution already posted for <8 ...user is asking for java 8..
– Arun Kumar
5 hours ago
in question solution already posted for <8 ...user is asking for java 8..
– Arun Kumar
5 hours ago
11
11
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
5 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
5 hours ago
I usually dislike nested ternaries, but this looks pretty clean.
– JollyJoker
3 hours ago
I usually dislike nested ternaries, but this looks pretty clean.
– JollyJoker
3 hours ago
add a comment |
You can also use a loop:
String[] strings = {str1, str2, str3, str4};
for(String str : strings) {
s = str;
if(s != null) break;
}
add a comment |
You can also use a loop:
String[] strings = {str1, str2, str3, str4};
for(String str : strings) {
s = str;
if(s != null) break;
}
add a comment |
You can also use a loop:
String[] strings = {str1, str2, str3, str4};
for(String str : strings) {
s = str;
if(s != null) break;
}
You can also use a loop:
String[] strings = {str1, str2, str3, str4};
for(String str : strings) {
s = str;
if(s != null) break;
}
answered 5 hours ago
ernest_kernest_k
22.6k42546
22.6k42546
add a comment |
add a comment |
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)
1
orElsestr4
inspite of it being a null actually
– nullpointer
5 hours ago
add a comment |
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)
1
orElsestr4
inspite of it being a null actually
– nullpointer
5 hours ago
add a comment |
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)
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)
answered 5 hours ago
azroazro
11.2k41638
11.2k41638
1
orElsestr4
inspite of it being a null actually
– nullpointer
5 hours ago
add a comment |
1
orElsestr4
inspite of it being a null actually
– nullpointer
5 hours ago
1
1
orElse
str4
inspite of it being a null actually– nullpointer
5 hours ago
orElse
str4
inspite of it being a null actually– nullpointer
5 hours ago
add a comment |
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);
add a comment |
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);
add a comment |
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);
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);
edited 3 hours ago
answered 3 hours ago
walenwalen
3,66211538
3,66211538
add a comment |
add a comment |
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;
}
}
add a comment |
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;
}
}
add a comment |
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;
}
}
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;
}
}
answered 5 hours ago
Daniel ChewDaniel Chew
13
13
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54800817%2fmultiple-null-checks-in-java8%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
3
Java9
or
syntaxString s = Optional.ofNullable(str1) .or(() -> Optional.ofNullable(str2)) .or(() -> Optional.ofNullable(str3)) .orElse(str4);
looks not as good as theStream.of
I would sya.– nullpointer
5 hours ago
Optional.ofNullable
is in Java-8 only, i guess.– Common Man
5 hours ago
1
@OleV.V. Nothing wrong, the OP is already aware of it and is seeking something specific to Java-8.
– nullpointer
4 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
3 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
12 mins ago