Open In App

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

Last Updated : 09 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Java
// Java Program to get the Index of 
// Specified Element in an Array
public class FindIndex {
  
    public static void main(String[] args) {
      
        int[] n = {1, 2, 3, 4, 5};
        int t = 3;
        
        for (int i = 0; i < n.length; i++) {
          
            // Check if the current element 
            // matches the target
            if (n[i] == t) { 
                System.out.println("Element found at index: " + i);
                return;
            }
        }
        System.out.println("Element not found in the array.");
    }
}

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.

Java
// Java Program to get the Index of Specified Element 
// in an Array using a Utility Function
public class FindIndex {
  
    public static int getIndex(int[] arr, int t) {
      
        if (arr != null) {
            for (int i = 0; i < arr.length; i++) {
                if (arr[i] == t) {
                    return i;    // Return index if element is found
                }
            }
        }
        return -1;      // Return -1 if element is not found
    }

    public static void main(String[] args) {
      
        int[] n = {1, 2, 3, 4, 5};
        int t = 3;
        int i = getIndex(n, t);

        if (i != -1) {
            System.out.println("Element found at index: " + i);
        } else {
            System.out.println("Element not found.");
        }
    }
}

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.

Java
// Java Program to get the Index of Specified Element 
// in an Array using Arrays.asList()
import java.util.Arrays;

public class FindIndex {
  
    public static void main(String[] args) {
      
        String[] n = {"Alice", "Bob", "Charlie", "David"};
        String t = "Charlie";

        int i = Arrays.asList(n).indexOf(t);   // Get index of target element
        if (i != -1) {
            System.out.println("Element found at index: " + i);
        } else {
            System.out.println("Element not found.");
        }
    }
}

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.

Java
// Java Program to get the Index of Specified Element 
// in an Array using Streams
import java.util.stream.IntStream;

public class FindIndex {
  
    public static void main(String[] args) {
      
        int[] n = {1, 2, 3, 4, 5};
        int t = 3;

        int ind = IntStream.range(0, n.length) // Create a range of indices
                             .filter(i -> n[i] == t) // Filter matching indices
                             .findFirst() // Get the first match
                             .orElse(-1); // Default to -1 if not found

        if (ind != -1) {
            System.out.println("Element found at index: " + ind);
        } else {
            System.out.println("Element not found.");
        }
    }
}

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.

Next Article
Article Tags :
Practice Tags :

Similar Reads