VOOZH about

URL: https://www.geeksforgeeks.org/java/how-to-get-the-index-of-a-specified-element-in-an-array-in-java/

⇱ How to Get the Index of a Specified Element in an Array in Java? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Get the Index of a Specified Element in an Array in Java?

Last Updated : 23 Jul, 2025

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.


Output
Element found at index: 2

Other Methods to Get the Index of a Specified Element

1. Using a Utility Function

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.


Output
Element found at index: 2

Note: if (arr != null), this ensures the array is not null to avoid a NullPointerException.

2. Using Arrays.asList() for Object Arrays

For 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.


Output
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.

3. Using Streams (Java 8+)

Streams can be useful for advanced scenarios where we need to filter or process elements while finding the index.


Output
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.

When to Use Which Method

  • Use for loop for simple and effective for basic needs.
  • Use utility function to improve code reuse and readability.
  • Arrays.asList() for non-primitive arrays is efficient for object arrays.
  • Use Streams for more advanced and functional programming approaches.
Comment
Article Tags:
Article Tags: