Is there any method that will check if the List is not empty and has one object which is not null?
Is there any better alternative for the following code
if( !list.isEmpty() && list.get(0) != null){
...
}
Please let me know if this piece of code can be improved in any way.
I guess you could try with java 8
if (list.stream().anyMatch(e -> e != null)) {... }
Your code doesn't work. What happens if the null
element is the second or the third?
A simple way is to use the method contains
:
Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
If you need to check if it exists exactly one NOT null element here is the code you need to write:
int countNull = 0;
for (Object obj : list) {
if (obj == null) {
countNull++;
}
}
if (countNull == list.size() - 1) {
// Contains exactly one not null element
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With