Compacting if else statement into shorter more elegant code [duplicate] - java

This question already has answers here:
How to get the first non-null value in Java?
(13 answers)
Closed 4 years ago.
I have the following if-else block, and I'm wondering if there's a more elegant way this code could be written... I am using Java 8
if(valueString != null) {
return valueString;
}
else if(valueInt != null) {
return String.valueOf(valueInt);
}
else if(valueFloat != null) {
return String.valueOf(valueFloat);
}
else if(valueDate != null){
return String.valueOf(valueDate);
}
else if(valueBit != null) {
return String.valueOf(valueBit);
}
else {
return null;
}

Use a stream and go through all the values and return null if none of them is not null.
return Stream.of(valueString, valueInt, valueFloat, valueDate, valueBit)
.filter(Objects::nonNull)
.map(String::valueOf)
.findFirst().orElse(null);

Related

How to combine isEmpty, isBlank and null check while validating string in java [duplicate]

This question already has answers here:
how to check multiple string value are empty or blank at one shot using java
(2 answers)
Closed 1 year ago.
I'm validating given string is null, isEmpty or isBlank and I've use case where I've to check either productId or productItem should present or productName and productPrice should contains value. For that I've written below if condition but it looks very clumsy and not readable. Can someone please help me how can we simplify this if condition and write in more readable format.
public class validate {
public static void main(String[] args) {
String productId = "";
String productItem = "";
String productName = "Apple";
String productPrice = "1500";
if ((!productId.isEmpty() && !productId.isBlank() && productId != null
|| !productItem.isEmpty() && !productItem.isBlank() && productItem != null)
|| (!productName.isEmpty() && !productName.isBlank() && productName != null
&& !productPrice.isEmpty() && !productPrice.isBlank() && productPrice != null)) {
System.out.println("valid");
} else {
System.out.println("not valid");
}
}
}
In general, you can often simplify code by defining auxiliary methods.
Define this helper:
boolean isNullEmptyOrBlank(String s) {
return s == null || s.isEmpty() || s.isBlank());
}
then
if (isNullEmptyOrBlank(productId) && isNullEmptyOrBlank(productItem) && isNullOrEmptyOrBlank(productName)) {
// invalid - unknown product
}
else if (isNullOrEmptyOrBlank(productValue)) {
// invalid - unknown price
}
else {
// valid
}
I'm not sure if I got your intended logic correct, but you should get the idea.
In practice, I'd probably decide isNullEmptyOrBlank was a clunky name, and call it something like isSet instead.

Java check if one of two variables is null and return the not null variable [duplicate]

This question already has answers here:
How to get the first non-null value in Java?
(13 answers)
Closed 1 year ago.
What is the best way to write something like this in shorthand using operators, if possible?
if (l1 == null && l2 == null){
return null;
}
else if (l1 == null){
return l2;
}
else if (l2 == null){
return l1;
}
For me, it's this:
return l1 == null ? l2 : l1;
If l1 & l2 are null, it will return null. Else, if at least one of them it not null, it will return the one that is defined.
For two variables it's probably overkill but a functional way of doing so can be:
return Optional(l1)
.orElse(l2)
.getOrElse(null);
Self-explanatory I believe.

Cleaner way to check if null [duplicate]

This question already has answers here:
How to get the first non-null value in Java?
(13 answers)
Closed 6 years ago.
I have a class that holds a couple of byte arrays, some could be empty some not. And I want to return the first non null array (if there is one) or null if there isn't. But the code just seems so redundant and ugly.
public byte[] getFirstPhoto() {
if (photo1 != null) {
return photo1;
}
if (photo2 != null) {
return photo2;
}
if (photo3 != null) {
return photo3;
}
if(videoThumbnail != null){
return videoThumbnail;
}
return null;
}
Is there anyway to clean that up, or not really?
Yes. Write a method something like this:
public byte[] firstNonNull(byte[]... arrays) {
for (byte[] array : arrays) {
if (array != null)
return array;
}
return null;
}
Then call this function passing in your four arrays in the proper order.

If-condition never executes despite correct condition [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I have a simple piece of code to validate a username and a password.
public boolean isValid(String u, String p) {
if (u=="admin" && p=="password1") {
return true;
} else if (u=="user" && p=="password2") {
return true;
} else {
return false;
}
}
I've tried debugging it, and when it runs, u has the value "admin" and p has the value "password1", but it just skips the first condition. I must have done something wrong, but I can't figure out what.
== should not be used for String comparison. Use equals() instead.

Intersecting 2 binary trees - throws Stack Overflow error [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Intersection of 2 binary trees throws Stack Overflow error
Java Binary Search Trees
I need to return a new OrderedSet that contains the overlapping elements of the two binary trees. I think it is the private OrderedSet that is throwing the error, at least that is what eclipse is telling me.
private OrderedSet<E> resultIntersect = new OrderedSet<E>();
public OrderedSet<E> intersection(OrderedSet<E> other) {
OrderedSet<E> result = new OrderedSet<E>();
result = resultIntersect;
return result;
}
private void intersection(OrderedSet<E> other, TreeNode t) {
if (other.contains(t.data)) {
resultIntersect.insert(t.data);
}
if(t.left != null)
intersection(other, t.left);
if(t.right != null)
intersection(other, t.right);
}
**EDIT
I can't seem to get it to return correctly. How can I get the private method to return the result correctly?
public OrderedSet<E> intersection(OrderedSet<E> other) {
OrderedSet<E> result = new OrderedSet<E>();
result = intersection(other, root, result);
return result;
}
private OrderedSet<E> intersection(OrderedSet<E> other, TreeNode t, OrderedSet<E> result) {
if (other.contains(t.data)) {
result.insert(t.data);
}
if (t.left != null && t.right != null)
return intersection(other, t.left, result) + intersection(other, t.right, result);
if (t.left != null)
intersection(other, t.left, result);
if (t.right != null)
return intersection(other, t.right, result);
else
return result;
}
I answered in your other question, but for completeness, here it is again.
Although you don't mention it, and your posted code did not include it, I'm guessing OrderedSet<E> resultIntersection is a field in OrderedSet<E>. In which case when you create a new instance of OrderedSet<E> it creates another instance of an OrderedSet<E> to assign to resultIntersection. That then has it's own resultIntersection that needs an instance of OrderedSet<E> creating, and so on...
The fix would be to remove resultIntersection and find some other way of implementing intersection. It's generally bad practice to have methods passing data around by manipulating shared state when it's not necessary, as it makes the logic more difficult to follow and can lead to multi-threading issues.

Categories

Resources