![]() |
VOOZH | about |
In Java, to find the index of a specific element in an array, we can iterate through it and checking each element. There are several ways to achieve this, including using loops, utility functions, Arrays.asList() for non-primitive arrays, and Streams.
Example: The simplest way is to iterate through the array with a for loop and compare each element to the target.
Element found at index: 2
Encapsulating the logic in a utility function improves code reusability and readability. This method allows us to check the index of any target element in an array.
Element found at index: 2
Note: if (arr != null), this ensures the array is not null to avoid a NullPointerException.
Arrays.asList() for Object ArraysFor arrays of non-primitive types (like String or Integer), Arrays.asList() can be used to convert the array into a list. The indexOf() method of the list is then used to find the element's index.
Element found at index: 2
Explanation: The Arrays.asList(names) converts the array to a List. It works only for object arrays. The indexOf(target) returns the index of the first occurrence of the target in the list or -1 if not found.
Streams can be useful for advanced scenarios where we need to filter or process elements while finding the index.
Element found at index: 2
Explanation: The .filter(i -> numbers[i] == target) filters indices, where the element matches the target. The .findFirst() returns the first matching index if any. The .orElse(-1) provides a default value (-1) if no match is found.
Arrays.asList() for non-primitive arrays is efficient for object arrays.