简体   繁体   中英

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?

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 */);

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM