How to Get the Index of a Specified Element in an Array in Java?
Last Updated :
09 Dec, 2024
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.");
}
}
OutputElement 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.");
}
}
}
OutputElement found at index: 2
Note:
if (arr != null), this
e
nsures 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.");
}
}
}
OutputElement found at index: 2
Explanation: The
Arrays.asList(names) c
onverts the array to a List
. It works only for object arrays.
The
indexOf(target) r
eturns 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.");
}
}
}
OutputElement found at index: 2
Explanation:
The
.filter(i -> numbers[i] == target)
f
ilters 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.
Similar Reads
How to Get Last Element in Array in Java? In Java, to get the last element in an array, we can access the element at the index array.length - 1 using array indexing. The length property of the array provides its total size, and subtracting one from it gives the index of the last element.Example 1: Here, we will access the last element in an
2 min read
How to Get First Element in Array in Java? In Java, to get the first element in an array, we can access the element at index 0 using array indexing. Example 1: Below is a simple example that demonstrates how to access the element at index 0 in an array.Javapublic class Geeks { public static void main(String[] args) { // Declare and initializ
2 min read
Find first and last element of ArrayList in java Prerequisite: ArrayList in Java Given an ArrayList, the task is to get the first and last element of the ArrayList in Java, Examples: Input: ArrayList = [1, 2, 3, 4] Output: First = 1, Last = 4 Input: ArrayList = [12, 23, 34, 45, 57, 67, 89] Output: First = 12, Last = 89 Approach: Get the ArrayList
2 min read
Check If a Value is Present in an Array in Java Given an array of Integers and a key element. Our task is to check whether the key element is present in the array. If the element (key) is present in the array, return true; otherwise, return false.Example: Input: arr[] = [3, 5, 7, 2, 6, 10], key = 7Output: Is 7 present in the array: trueInput: arr
8 min read
Get first and last elements from ArrayList in Java Given an array list, find the first and last elements of it. Examples: Input : aList = {10, 30, 20, 14, 2} Output : First = 10, Last = 2 Input : aList = {10, 30, 40, 50, 60} Output : First = 10, Last = 60 The last element is at index, size - 1 and the first element is stored at index 0. If we know h
3 min read