[java] How to find the index of an element in an int array?

How can I find an index of a certain value in a Java array of type int?

I tried using Arrays.binarySearch on my unsorted array, it only sometimes gives the correct answer.

This question is related to java arrays search indexing

The answer is


Integer[] array = {1, 2, 3, 4, 5, 6};

for (int i = 0; i < array.length; i++) {
    if (array[i] == 4) {
        system.out.println(i);
        break;
    }
}

You can use modern Java to solve this problem. Please use the code below:

static int findIndexOf(int V, int[] arr) {
    return IntStream.range(0, arr.length)
                    .filter(i->arr[i]==V)
                    .findFirst()
                    .getAsInt();
}


Simple:

public int getArrayIndex(int[] arr,int value) {
    for(int i=0;i<arr.length;i++)
        if(arr[i]==value) return i;
    return -1;
}

You can do it like this:

 public class Test {

public static int Tab[]  = {33,44,55,66,7,88,44,11,23,45,32,12,95};
public static int search = 23;

public static void main(String[] args) {
    long stop = 0;
    long time = 0;
    long start = 0;
    start = System.nanoTime();
    int index = getIndexOf(search,Tab);
    stop = System.nanoTime();
    time = stop - start;
    System.out.println("equal to took in nano seconds ="+time);
    System.out.println("Index  of searched value is: "+index);
    System.out.println("De value of Tab with searched index is: "+Tab[index]);
    System.out.println("==========================================================");
    start = System.nanoTime();
    int Bindex = bitSearch(search,Tab);
    stop = System.nanoTime();
    time = stop - start;
    System.out.println("Binary search took nano seconds ="+time);
    System.out.println("Index  of searched value is: "+Bindex);
    System.out.println("De value of Tab with searched index is: "+Tab[Bindex]);
}



public static int getIndexOf( int toSearch, int[] tab ){
     int i = 0;
     while(!(tab[i] == toSearch) )
     {  i++; }
       return i; // or return tab[i];
   }
public static int bitSearch(int toSearch, int[] tab){
    int i = 0;
    for(;(toSearch^tab[i])!=0;i++){
    }
    return i;

}

}

Added a XOR :)


A look at the API and it says you have to sort the array first

So:

Arrays.sort(array);
Arrays.binarySearch(array, value);

If you don't want to sort the array:

public int find(double[] array, double value) {
    for(int i=0; i<array.length; i++) 
         if(array[i] == value)
             return i;
}

Another option if you are using Guava Collections is Ints.indexOf

// Perfect storm:
final int needle = 42;
final int[] haystack = [1, 2, 3, 42];

// Spoiler alert: index == 3
final int index = Ints.indexOf(haystack, needle);

This is a great choice when space, time and code reuse are at a premium. It is also very terse.


Copy this method into your class

 public int getArrayIndex(int[] arr,int value) {

        int k=0;
        for(int i=0;i<arr.length;i++){

            if(arr[i]==value){
                k=i;
                break;
            }
        }
    return k;
}

Call this method with pass two perameters Array and value and store its return value in a integer variable.

int indexNum = getArrayIndex(array,value);

Thank you


You can either walk through the array until you find the index you're looking for, or use a List instead. Note that you can transform the array into a list with asList().


    Integer[] arr = { 0, 1, 1, 2, 3, 5, 8, 13, 21 };
    List<Integer> arrlst = Arrays.asList(arr);
    System.out.println(arrlst.lastIndexOf(1));

You need to sort values before using binary search. Otherwise, the manual way is to try all ints in your tab.

public int getIndexOf( int toSearch, int[] tab )
{
  for( int i=0; i< tab.length ; i ++ )
    if( tab[ i ] == toSearch)
     return i;

  return -1;
}//met

An alternative method could be to map all index for each value in a map.

tab[ index ] = value;
if( map.get( value) == null || map.get( value) > index )
    map.put( value, index );

and then map.get(value) to get the index.

Regards, Stéphane

@pst, thanks for your comments. Can you post an other alternative method ?


In case anyone is still looking for the answer-

  1. You can use ArrayUtils.indexOf() from the [Apache Commons Library][1].

  2. If you are using Java 8 you can also use the Strean API:

    public static int indexOf(int[] array, int valueToFind) {
        if (array == null) {
            return -1;
        }
        return IntStream.range(0, array.length)
                .filter(i -> valueToFind == array[i])
                .findFirst()
                .orElse(-1);
    }
    

    [1]: https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/ArrayUtils.html#indexOf(int[],%20int)


Integer[] array = {1,2,3,4,5,6};

Arrays.asList(array).indexOf(4);

Note that this solution is threadsafe because it creates a new object of type List.

Also you don't want to invoke this in a loop or something like that since you would be creating a new object every time


ArrayUtils.indexOf(array, value);
Ints.indexOf(array, value);
Arrays.asList(array).indexOf(value);

In the main method using for loops: -the third for loop in my example is the answer to this question. -in my example I made an array of 20 random integers, assigned a variable the smallest number, and stopped the loop when the location of the array reached the smallest value while counting the number of loops.

import java.util.Random;
public class scratch {
    public static void main(String[] args){
        Random rnd = new Random();
        int randomIntegers[] = new int[20];
        double smallest = randomIntegers[0];
        int location = 0;

        for(int i = 0; i < randomIntegers.length; i++){             // fills array with random integers
            randomIntegers[i] = rnd.nextInt(99) + 1;
            System.out.println(" --" + i + "-- " + randomIntegers[i]);
        }

        for (int i = 0; i < randomIntegers.length; i++){            // get the location of smallest number in the array 
            if(randomIntegers[i] < smallest){
                smallest = randomIntegers[i];                 
            }
        }

        for (int i = 0; i < randomIntegers.length; i++){                
            if(randomIntegers[i] == smallest){                      //break the loop when array location value == <smallest>
                break;
            }
            location ++;
        }
        System.out.println("location: " + location + "\nsmallest: " + smallest);
    }
}

Code outputs all the numbers and their locations, and the location of the smallest number followed by the smallest number.


The easiest way is to iterate. For example we want to find the minimum value of array and it's index:

public static Pair<Integer, Integer> getMinimumAndIndex(int[] array) {
        int min = array[0];
        int index = 0;
        for (int i = 1; i < array.length; i++) {
            if (array[i] < min) {
                min = array[i];
                index = i;
            }

            return new Pair<min, index>;

This way you test all array values and if some of them is minimum you also know minimums index. It can work the same with searching some value:

public static int indexOfNumber(int[] array) {
        int index = 0;
        for (int i = 0; i < array.length; i++) {
            if (array[i] == 77) {        // here you pass some value for example 77
                index = i;
            }
        }
        return index;
    }

/**
     * Method to get the index of the given item from the list
     * @param stringArray
     * @param name
     * @return index of the item if item exists else return -1
     */
    public static int getIndexOfItemInArray(String[] stringArray, String name) {
        if (stringArray != null && stringArray.length > 0) {
            ArrayList<String> list = new ArrayList<String>(Arrays.asList(stringArray));
            int index = list.indexOf(name);
            list.clear();
            return index;
        }
        return -1;
    }

static int[] getIndex(int[] data, int number) {
    int[] positions = new int[data.length];
    if (data.length > 0) {
        int counter = 0;
        for(int i =0; i < data.length; i++) {
            if(data[i] == number){
                positions[counter] = i;
                counter++;
            }
        }
    }
    return positions;
}

Binary search: Binary search can also be used to find the index of the array element in an array. But the binary search can only be used if the array is sorted. Java provides us with an inbuilt function which can be found in the Arrays library of Java which will rreturn the index if the element is present, else it returns -1. The complexity will be O(log n). Below is the implementation of Binary search.

public static int findIndex(int arr[], int t) { 
   int index = Arrays.binarySearch(arr, t); 
   return (index < 0) ? -1 : index; 
} 

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array? Find a file by name in Visual Studio Code Search all the occurrences of a string in the entire project in Android Studio Java List.contains(Object with field value equal to x) Trigger an action after selection select2 How can I search for a commit message on GitHub? SQL search multiple values in same field Find a string by searching all tables in SQL Server Management Studio 2008 Search File And Find Exact Match And Print Line? Java - Search for files in a directory How to put a delay on AngularJS instant search?

Examples related to indexing

numpy array TypeError: only integer scalar arrays can be converted to a scalar index How to print a specific row of a pandas DataFrame? What does 'index 0 is out of bounds for axis 0 with size 0' mean? How does String.Index work in Swift Pandas KeyError: value not in index Update row values where certain condition is met in pandas Pandas split DataFrame by column value Rebuild all indexes in a Database How are iloc and loc different? pandas loc vs. iloc vs. at vs. iat?