Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Find first and last element of ArrayList in java
Next article icon

Find the Index of an Array Element in Java

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

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));     } } 

Output
6 

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));              } } 

Output
6 

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));     } } 

Output
6 

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));     } } 

Output
6 

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


Next Article
Find first and last element of ArrayList in java

T

Tarandeep Singh 4
Improve
Article Tags :
  • Java
  • Java-Array-Programs
  • Java-Arrays
Practice Tags :
  • Java

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences