Ksenia
Ksenia

Reputation: 3753

How to get index of the first not null array element?

Is there any nice way to get the index of the first not null String array element? Yes, you can write

int index;
for (int i = 0; i < arr.length; i++) {
   if (arr[i] != null) {
       index = i;
       break;
   }
}

but maybe there is possible to do it in a more beautiful manner? For example, you can use ObjectUtils.firstNonNull method to get the first not null element of the array, maybe there's something similar to obtain index?

Upvotes: 1

Views: 8209

Answers (5)

William Leung
William Leung

Reputation: 1653

int last = list.size() - 1;
for (; last >= 0 && list.get(last) == null; last--) { /* no-op */ }

Upvotes: 0

Alptekin T.
Alptekin T.

Reputation: 115

Object[] dizi = { 1, 2, 3, 4, 5, 6, null, 8, 9, 10 };

    Object t = null;
    int len = dizi.length;
    System.out.println(IntStream.range(0, len).filter(i -> t == dizi[i]).findFirst().orElse(-1)); // can't find.);

Upvotes: 0

yegodm
yegodm

Reputation: 1044

For example, like that in Java version earlier than 8:

static final Object ANY_NOT_NULL = new Object()
{
    @Override
    public boolean equals(final Object obj)
    {
        return obj != null;
    }
};

public static int firstIndexOfNotNull(Object... values)
{
    return Arrays.asList(values).indexOf(ANY_NOT_NULL);
}

Upvotes: 1

Schidu Luca
Schidu Luca

Reputation: 3947

If you are using Java 9 there is a method called takeWhile(). you can use it in your array of numbers like so.

long index = Arrays.stream(yourArray).takeWhile(Objects::isNull).count();

Edit

In case there are no non-null elements index will be equal to the length of the array.

You can make a check for it.

if(index == array.length) {
    index = -1;
}

Upvotes: 3

Mureinik
Mureinik

Reputation: 311188

One trick is to create a stream of indexes, and then find the first one that points to a non-null value:

int index =
    IntStream.range(0, arr.length)
             .filter(i -> arr[i] != null)
             .findFirst()
             .orElse(-1 /* Or some other default */);

Upvotes: 8

Related Questions