For primitive arrays
Starting with Java 8, the general purpose solution for a primitive array arr
, and a value to search val
, is:
public static int indexOf(char[] arr, char val) {
return IntStream.range(0, arr.length).filter(i -> arr[i] == val).findFirst().orElse(-1);
}
This code creates a stream over the indexes of the array with IntStream.range
, filters the indexes to keep only those where the array's element at that index is equal to the value searched and finally keeps the first one matched with findFirst
. findFirst
returns an OptionalInt
, as it is possible that no matching indexes were found. So we invoke orElse(-1)
to either return the value found or -1
if none were found.
Overloads can be added for int[]
, long[]
, etc. The body of the method will remain the same.
For Object arrays
For object arrays, like String[]
, we could use the same idea and have the filtering step using the equals
method, or Objects.equals
to consider two null
elements equal, instead of ==
.
But we can do it in a simpler manner with:
public static <T> int indexOf(T[] arr, T val) {
return Arrays.asList(arr).indexOf(val);
}
This creates a list wrapper for the input array using Arrays.asList
and searches the index of the element with indexOf
.
This solution does not work for primitive arrays, as shown here: a primitive array like int[]
is not an Object[]
but an Object
; as such, invoking asList
on it creates a list of a single element, which is the given array, not a list of the elements of the array.