Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if arraylist contains only nulls

Tags:

java

arraylist

I think there has to be a better way of doing this.. I have a call to a function that returns an ArrayList. If that ArrayList only returns 10 null items (the default), is there a way of checking this without iterating through all 10 items to see if they are null?

like image 973
mike628 Avatar asked Jan 04 '13 18:01

mike628


People also ask

How do you check if an ArrayList contains null value?

v == null : o. equals(v) ). i.e. if o is null , it returns true only if one element is null in the ArrayList. If o is not null , it returns true only if at least one element equal to v.

How do you check if a list contains null value?

To check if there is a null value in an object or array, use the concept of includes().

Does isEmpty check for null ArrayList?

isEmpty() doesn't check if a list is null . If you are using the Spring framework you can use the CollectionUtils class to check if a list is empty or not.

Can ArrayList contain null Java?

An ArrayList element can be an object reference or the value null . When a cell contains null , the cell is not considered to be empty. The picture shows empty cells with an "X" and cells that contain a null with null .


2 Answers

As of Java 8, you can use Streams like this:

boolean nullsOnly = list.stream().noneMatch(Objects::nonNull);

Which is equal to:

boolean nullsOnly = list.stream().allMatch(x -> x == null)

And here you can see the more general way of testing that any list matches a given Predicate:

list.stream().allMatch(x -> /* Some testing function. */)
like image 135
Fabian Damken Avatar answered Sep 17 '22 20:09

Fabian Damken


The best way to check is by using boolean allMatch(Predicate<? super T> predicate); This Returns whether all elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty then true is returned and the predicate is not evaluated.

 boolean hasAllNulls = list.stream().allMatch(Objects::isNull)
like image 36
v8-E Avatar answered Sep 18 '22 20:09

v8-E