Cleaner way to check if null [duplicate] - java

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.

Related

Create a new variable and check if it's null in one if [duplicate]

This question already has answers here:
What does an assignment expression evaluate to in Java?
(5 answers)
Closed 3 years ago.
Can I do something like this?
if(variable = class.GetVariable() != null){
variable.doSomething()
}
As I said in the comments I'm doing this with a HttpSession, so my goal is to check if there is a parameter in the session with a specific name and if it is do something.
You can, so long as variable has already been defined and you add additional brackets:
Foo variable;
if ((variable = GetVariable()) != null) {
variable.doSomething();
}
You tend not to see this pattern often as it's not the most readable, but it is often seen when reading from a BufferedReader line by line (as it provides a convenient, quick way to read lines until there aren't any):
String line;
while((line=reader.readLine())!=null) {
//Process each line
}
!= has precedence over =, so here the code means assigning the boolean value resulting from class.GetVariable() != null to the variable variable :
if(variable = class.GetVariable() != null){
...
}
That is not what you want.
So enclose the assignment between () to set explicitly the precedence :
String variable = null;
if( (variable = class.GetVariable()) != null){
variable.doSomething()
}
As long as you define the variable first, yes but you must put them in parenties:
MyObject variable;
if( ( variable = class.GetVariable()) != null){
variable.doSomething();
}

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

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);

java.util.NoSuchElementException: No value present Java 8 Lambda [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I got this. But my list is not empty and they have element with code "ADPL". Why this return me NoSuchElement ?
String retour = CodeExecutionChaine.A.getCode();
if (!lstChaines.isEmpty()) {
retour = lstChaines.stream()
.filter(t -> t.getNomChaine() == Chaines.ADPL.getCode())
.map(Chaine::getStatutChaine)
.findFirst()
.orElse(CodeExecutionChaine.A.getCode());
The enum Chaines
public enum Chaines {
ADPL("ADPL"),
ADIL("ADIL"),
ADSL("ADSL");
private String code = "";
Chaines(String code) {
this.code = code;
}
public String getCode() {
return this.code;
}
}
This is the same for CodeExecutionChaine
Change t -> t.getNomChaine() == Chaines.ADPL.getCode() to t -> t.equals(Chaines.ADPL.getCode()).
== checks for identity. Therefore, == will result into true only if two references point to the same object. On the other hand, equals checks for equality. Two references that don't point to the same object but have similar properties are still considered equal. You get a NoSuchElementException because you used == to filter your Stream which resulted in zero elements satisfying the condition.

Optimistic way of checking null references in java [duplicate]

This question already has answers here:
Avoiding NullPointerException in Java
(66 answers)
Closed 7 years ago.
Can any Java proficient / expert suggest me what is the optimistic way of checking null reference or objects before using it to avoids NullPointerException?
In my code I've more than 100 fields and most of them are required in order to pass value in request, but I need to perform null checks every time before passing it in request to avoid NullPointerException
I have shown below a little piece of code where I'm checking for null values every time for each field (lets say of more 70 times in my one file) which looks not good, code become very ugly and unreadable. Is there any way by which we can write method and perform null object checks through it?
Basically I'm looking better, Optimistic and faster way for doing this, Any quick help is much needed.
if(amount != null && amount != "" && !amount.isEmpty())
AIMRequest.put("x_Amount", amount);
if(currency != null && currency != "" && !currency.isEmpty())
AIMRequest.put("x_Currency_Code", currency);
if(expDate != null && expDate != "" && !expDate.isEmpty())
AIMRequest.put("x_Exp_Date", expDate);
...........so on
add("x_Amount", amount);
add("x_Currency_Code", currency);
add("x_Exp_Date", expDate);
void add(String name, String value)
{
if(value!=null && !value.isEmpty())
AIMRequest.put(name, value);
}
According your if's, conditions you are comparing Strings, so make a method:
public boolean isValid(String s) {
return s != null && s != "" && !s.isEmpty();
}
If you want to compare objects with this methods change the signature public boolean isValid(Object o),
and your code will be clean as this:
if(isValid(amount))
AIMRequest.put("x_Amount", amount);
if(isValid(currency)
AIMRequest.put("x_Currency_Code", currency);
if(isValid(expDate)
AIMRequest.put("x_Exp_Date", expDate);
But if you can collect all objects in an array:
public boolean isValid(Object[] os) {
for (String s : os) {
boolean isValid = s != null && s != "" && !s.isEmpty();
if (!isValid) return false;
}
return true;
}

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