Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if the list contains at lease one non null object

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.

like image 346
codeMan Avatar asked Dec 23 '22 22:12

codeMan


2 Answers

I guess you could try with java 8

if (list.stream().anyMatch(e -> e != null)) {... }
like image 127
eric.v Avatar answered Dec 26 '22 12:12

eric.v


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
}
like image 21
Davide Lorenzo MARINO Avatar answered Dec 26 '22 10:12

Davide Lorenzo MARINO