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?
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.
To check if there is a null value in an object or array, use the concept of includes().
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.
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 .
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. */)
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)
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