September 2019
Intermediate to advanced
816 pages
18h 47m
English
For an array of primitives, the simplest implementation speaks for itself:
public static int findIndexOfElement(int[] arr, int toFind) { for (int i = 0; i < arr.length; i++) { if (arr[i] == toFind) { return i; } } return -1;}
Relying on Java 8 functional style, we can try to loop the array and filter the elements that match the given element. In the end, simply return the first found element:
public static int findIndexOfElement(int[] arr, int toFind) { return IntStream.range(0, arr.length) .filter(i -> toFind == arr[i]) .findFirst() .orElse(-1);}
For an array of Object, there are at least three approaches. In the first instance, we can rely on the equals() contract:
public static <T> int findIndexOfElementObject(T[] ...