Is there any nice way to get the index of the first non-null 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 some more beautiful way to do this? For example, for getting the first not null element of an array there is a method ObjectUtils.firstNonNull , maybe there is something similar for getting an index?

  • one
    Does this code work exactly? And if there is primitive? Therefore, the task becomes more interesting) - pavel
  • @pavel, well, I initially had an array of strings) - Ksenia
  • And what does not suit this method? - JVic
  • 2
    @pavel if an array of primitives, then there will be no nulls - Russtam

3 answers 3

You can write a loop a little shorter:

 int index = 0; while (index < arr.length && arr[index] == null) ++index; 

Or even:

 int index = -1; while (++index < arr.length && arr[index] == null) {} 

Or here's a variant with for (thanks @Qwertiy!):

 int index; for (index = 0; index < arr.length && arr[index] == null; ++index); 

You can also write your own method for this, using any of the methods above, or like this ( Ideone ):

 static <T> int firstNotNullIndex(T[] arr) { for (int i = 0; i < arr.length; ++i) if (arr[i] != null) return i; // или `return -1` return arr.length; } 
  • one
    int index = 0; for (; index < arr.length && arr[index] == null; ++index); - Qwertiy
  • @Qwertiy, yes, thanks! - diraria

Maybe so (java 8, for String) ?:

 Arrays.asList(array).indexOf(Arrays.stream(array).filter(Objects::nonNull).findFirst().get()) 
  • Will it be an index or a value? - Qwertiy
  • @Qweriy This will be an index. - Eugene Kirin
  • Oh, got it. There, the item is first searched, and then its index. Carefully read. - Qwertiy

In my opinion, here is the most elegant solution (thanks to the help of English-speaking SO):

 int titleIndex = IntStream.range(0, arr.length) .filter(i -> arr[i] != null) .findFirst().getAsInt(); 
  • 3
    Elegant syntactically? If I open IntStream guts, IntStream ’m afraid we won’t be happy - Barmaley
  • 2
    @Barmaley, well, yes, apparently, the elegant is only syntactically ... ( - Ksenia