Ways to check if an ArrayList contains only null values

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().


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);
}

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

Tags:

Java

Android