Find the Index of an Array Element in Java
Last Updated : 09 Dec, 2024
In Java, arrays are one of the most commonly used data structures for storing a collection of data. Here, we will find the position or you can index of a specific element in given array.
Example:
Input: a[] = { 5, 4, 6, 1, 3, 2, 7, 8, 9 }, element = 7 Output: 6
1. Using a Simple Loop
One of the simplest and most straightforward ways to find the index of an element in an array is by using a loop. You can iterate through the array and compare each element with the target element. When a match is found, you return the index.
Java // Java program to find index of array // element using a while loop import java.util.*; public class Geeks { // Linear-search function to find the index of an element public static int findIndex(int a[], int t) { if (a == null) return -1; int len = a.length; int i = 0; // traverse in the array while (i < len) { // if the i-th element is t // then return the index if (a[i] == t) { return i; } else { i = i + 1; } } return -1; } public static void main(String[] args) { int[] a = { 5, 4, 6, 1, 3, 2, 7, 8, 9 }; int t = 7; // find the index of 7 System.out.println(findIndex(a, t)); } }
Here, we have used linear search in an array, the element can be found in O(N) complexity.
2. Using Arrays.binarySearch() for Sorted Arrays
Arrays.binarySearch() method can also be used in case if array is already sorted. This will be faster method than above one as this has time complexity of O(log n).
Java // Java program to find index of an array // element using Arrays.binarySearch() import java.util.Arrays; public class Geeks{ public static int findIndex(int arr[], int t){ int index = Arrays.binarySearch(arr, t); return (index < 0) ? -1 : index; } public static void main(String[] args){ int[] a = { 1, 2, 3, 4, 5, 6, 7 }; int t = 7; // find the index of 5 System.out.println(findIndex(a, t)); } }
3. Using Guava Library
Guava is an open source, Java-based library developed by Google. It provides utility methods for collections, caching, primitives support, concurrency, common annotations, string processing, I/O, and validations. Guava provides several-utility class pertaining to be primitive like Ints for int, Longs for long, Doubles for double etc. Each utility class has an indexOf() method that returns the index of the first appearance of the element in array.
Java // Java program to find index of an array // element using Guava Library import java.util.List; import com.google.common.primitives.Ints; public class Geeks{ // Function to find the index of an element using public static int findIndex(int a[], int t){ return Ints.indexOf(a, t); } public static void main(String[] args){ int[] a = { 5, 4, 6, 1, 3, 2, 7, 8, 9 }; int t=5; System.out.println(findIndex(a, t)); } }
Output:
6
4. Using Stream API
Stream is a new abstract layer introduced in Java 8. Using stream, you can process data in a declarative way similar to SQL statements. The stream represents a sequence of objects from a source, which supports aggregate operations. In order to find the index of an element Stream package provides utility, IntStream. Using the length of an array we can get an IntStream of array indices from 0 to n-1, where n is the length of an array.
Java // Java program to find index of an array // element using Stream API import java.util.stream.IntStream; public class Geeks { // Function to find the index of an element public static int findIndex(int arr[], int t){ int len = arr.length; return IntStream.range(0, len) .filter(i -> t == arr[i]) .findFirst() // first occurrence .orElse(-1); // No element found } public static void main(String[] args){ int[] a = { 5, 4, 6, 1, 3, 2, 7, 8, 9 }; int t = 7; System.out.println(findIndex(a, t)); } }
5. Using ArrayList
In this approach, we will convert the array into ArrayList, and then we will use the indexOf method of ArrayList to get the index of the element.
Java // Java program to find index of an array // element using ArrayList indexOf() Method import java.util.ArrayList; public class Geeks { public static int findIndex(int arr[], int t){ ArrayList<Integer> clist = new ArrayList<>(); // adding elements of array // to ArrayList for (int i : arr) clist.add(i); return clist.indexOf(t); } public static void main(String[] args){ int[] a = { 5, 4, 6, 1, 3, 2, 7, 8, 9 }; int t = 7; System.out.println(findIndex(a, t)); } }
6. Using Recursion
We will use recursion to find the first index of the given element.
Java // Java program to find index of an array // element using Recursion public class Geeks { public static int index(int arr[], int t, int start){ if (start == arr.length) return -1; // if element at index start equals t // we return start if (arr[start] == t) return start; return index(arr, t, start + 1); } public static int findIndex(int arr[], int t){ return index(arr, t, 0); } public static void main(String[] args) { int[] a = { 5, 4, 6, 1, 3, 2, 7, 8, 9 }; int t = 7; System.out.println(findIndex(a, t)); } }
Output:
Index position of 5 is: 0 Index position of 7 is: 6
Similar Reads
Find the Middle Element of an Array or List
Given an array or a list of elements. The task is to find the middle element of given array or list of elements. If the array size is odd, return the single middle element. If the array size is even, return the two middle elements. ExampleInput: arr = {1, 2, 3, 4, 5}Output: 3 Input: arr = {7, 8, 9,
9 min read
How to Find Index of Element in Array in MATLAB?
In MATLAB, the arrays are used to represent the information and data. You can use indexing to access the elements of the array. Â In MATLAB the array indexing starts from 1. To find the index of the element in the array, you can use the find() function. Using the find() function you can find the indi
4 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
How to find the index of an element in an array using PHP ?
In this article, we will discuss how to find the index of an element in an array in PHP. Array indexing starts from 0 to n-1. Here we have some common approaches Table of Content Using array_search() FunctionUsing array_flip()Using a custom functionUsing a foreach LoopUsing array_keys FunctionUsing
6 min read
JavaScript - Find Index of a Value in Array
Here are some effective methods to find the array index with a value in JavaScript. Using indexOf() - Most Used indexOf() returns the first index of a specified value in an array, or -1 if the value is not found. [GFGTABS] JavaScript const a = [10, 20, 30, 40, 50]; // Find index of value 30 const in
2 min read
Array Index Out Of Bounds Exception in Java
In Java, ArrayIndexOutOfBoundsException is a Runtime Exception thrown only at runtime. The Java Compiler does not check for this error during the compilation of a program. It occurs when we try to access the element out of the index we are allowed to, i.e. index >= size of the array. Java support
4 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. [GFGTABS] Java public class Geeks { public static void main(String[] args) { // Declare a
2 min read
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 a
2 min read
Find the position of an element in a Java TreeMap
Given an element N and a TreeMap, the task is to find the position of this element in the given TreeMap in Java. Examples: Input: TreeMap = {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}, N = 20 Output: 2 Input: TreeMap = {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}, N = 5 Output: -1 Approach: T
2 min read
Searching in Array for a given element in Julia
Given an array (1D, 2D or 3D), and an element to look for in the array. If the element is present in the array, then print the position of the element in the array, else print "Element not found". In the recent updates to Julia, the developers have unified the search() and find() functions into a si
6 min read