简体   繁体   English

如何获取第一个非空数组元素的索引?

[英]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?比如你可以使用ObjectUtils.firstNonNull方法来获取数组的第一个非空元素,也许有类似的东西来获取索引?

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() .如果您使用的是Java 9 ,则有一个名为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:例如,在 Java 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[] 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.);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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