codeMan
codeMan

Reputation: 5758

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.

Upvotes: 6

Views: 8669

Answers (2)

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

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
}

Upvotes: 2

eric.v
eric.v

Reputation: 615

I guess you could try with java 8

if (list.stream().anyMatch(e -> e != null)) {... }

Upvotes: 9

Related Questions