Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ways to check if an ArrayList contains only null values

Tags:

java

android

I was looking through the code for an old Android application of mine, and I saw one thing I did to the effect of this:

        boolean emptyArray = true;
        for (int i = 0; i < array.size(); i++)
        {
            if (array.get(i) != null)
            {
                    emptyArray = false;
                    break;
            }
        }
        if (emptyArray == true)
        {
            return true;
        }
        return false;

There has to be a more efficient way of doing this -- but what is it?

emptyArray is defined as an ArrayList of Integers, which are inserted with a random number of null values (And later in the code, actual integer values).

Thanks!

like image 376
DMags Avatar asked Jun 05 '11 14:06

DMags


3 Answers

Well, you could use a lot less code for starters:

public boolean isAllNulls(Iterable<?> array) {
    for (Object element : array)
        if (element != null) return false;
    return true;
}

With this code, you can pass in a much wider variety of collections too.


Java 8 update:

public static boolean isAllNulls(Iterable<?> array) {
    return StreamSupport.stream(array.spliterator(), true).allMatch(o -> o == null);
}
like image 136
Bohemian Avatar answered Oct 30 '22 02:10

Bohemian


It's not detection of contains only null values but it maybe be enough to use just contains(null) method on your list.

like image 32
Matt Avatar answered Oct 30 '22 01:10

Matt


There is no more efficient way. The only thing is you can do, is write it in more elegant way:

List<Something> l;

boolean nonNullElemExist= false;
for (Something s: l) {
  if (s != null) {
     nonNullElemExist = true;
     break;
  }
}

// use of nonNullElemExist;

Actually, it is possible that this is more efficient, since it uses Iterator and the Hotspot compiler has more info to optimize instead using size() and get().

like image 6
Op De Cirkel Avatar answered Oct 30 '22 01:10

Op De Cirkel