I have an array and I need to check the number of elements which are not null.
For example:
String carlist[] =new String[50]
carlist[0] = ferrari
carlist[1] = bentley
//all other values will be null.
How do I find out the answer, 2, which is the number of occupied places?
This will give you the number of non-null elements in an array:
int count = 0;
for (String car : carlist) {
if (car != null) {
count++;
}
}
Alternatively, if the array is populated consecutively so there are no nulls until the end, and you're working with a large dataset, it may be more efficient to locate the first null with a binary search:
int count = Arrays.binarySearch(carlist, null, Comparator.nullsLast((a, b) -> 0));
if (count < 0) {
count = carlist.length;
}
This comparator basically says "ignore the relative order of the values and just assume nulls come last." If the search returns a positive value, that will be the index of the first null, which is equivalent to the length of the non-null segment. If it's negative, it means no nulls were found, so the non-null count is the same as the array length.