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

I am looking to find the index of a given element, knowing its contents, in Java.

I tried the following example, which does not work:

class masi { 
    public static void main( String[] args ) { 
        char[] list = {'m', 'e', 'y'};

        // should print 1
        System.out.println(list[] == "e");                    
    } 
}

Can anyone please explain what is wrong with this and what I need to do to fix it?

This question is related to java arrays indexing

The answer is


Simplest solution:

Convert array to list and you can get position of an element.

List<String> abcd  = Arrays.asList(yourArray);
int i = abcd.indexOf("abcd");

Other solution, you can iterator array:

int position = 0;
for (String obj : yourArray) {
    if (obj.equals("abcd") {
    return position;
    }
    position += 1;
} 

//OR
for (int i = 0; i < yourArray.length; i++) {
    if (obj.equals("abcd") {
       return i;
    }
}

This way you can use upto 'N' letters.

char[] a={ 'a', 'b', 'c', 'd', 'e' };
int indexOf=0;
for(int i=0;i<a.length;i++){
  if(a[i] != 'b'){
    indexOf++;
    }else{
    System.out.println("index of given: "+indexOf);
 }}

I believe the only sanest way to do this is to manually iterate through the array.

for (int i = 0; i < list.length; i++) {
  if (list[i] == 'e') {
    System.out.println(i);
    break;
  }
}

The problem with your code is that when you do

 list[] == "e"

you're asking if the array object (not the contents) is equal to the string "e", which is clearly not the case.

You'll want to iterate over the contents in order to do the check you want:

 for(String element : list) {
      if (element.equals("e")) {
           // do something here
      }
 }

For primitive arrays

Starting with Java 8, the general purpose solution for a primitive array arr, and a value to search val, is:

public static int indexOf(char[] arr, char val) {
    return IntStream.range(0, arr.length).filter(i -> arr[i] == val).findFirst().orElse(-1);
}

This code creates a stream over the indexes of the array with IntStream.range, filters the indexes to keep only those where the array's element at that index is equal to the value searched and finally keeps the first one matched with findFirst. findFirst returns an OptionalInt, as it is possible that no matching indexes were found. So we invoke orElse(-1) to either return the value found or -1 if none were found.

Overloads can be added for int[], long[], etc. The body of the method will remain the same.

For Object arrays

For object arrays, like String[], we could use the same idea and have the filtering step using the equals method, or Objects.equals to consider two null elements equal, instead of ==.

But we can do it in a simpler manner with:

public static <T> int indexOf(T[] arr, T val) {
    return Arrays.asList(arr).indexOf(val);
}

This creates a list wrapper for the input array using Arrays.asList and searches the index of the element with indexOf.

This solution does not work for primitive arrays, as shown here: a primitive array like int[] is not an Object[] but an Object; as such, invoking asList on it creates a list of a single element, which is the given array, not a list of the elements of the array.


That's not even valid syntax. And you're trying to compare to a string. For arrays you would have to walk the array yourself:

public class T {
  public static void main( String args[] ) {
    char[] list = {'m', 'e', 'y'};

    int index = -1;

    for (int i = 0; (i < list.length) && (index == -1); i++) {
        if (list[i] == 'e') {
            index = i;
        }
    }

    System.out.println(index);
  }
}

If you are using a collection, such as ArrayList<Character> you can also use the indexOf() method:

ArrayList<Character> list = new ArrayList<Character>();
list.add('m');
list.add('e');
list.add('y');

System.out.println(list.indexOf('e'));

There is also the Arrays class which shortens above code:

List list = Arrays.asList(new Character[] { 'm', 'e', 'y' });
System.out.println(list.indexOf('e'));

here is another example and how indexOf is working.

public int indexOf(Object target) {
    for (int i = 0; i < array.length; i++) {
        if (equals(target, array[i])) {
            return i;
        }
    }
    return -1;
}

This way should work, change "char" to "Character":

public static void main(String[] args){
  Character[] list = {'m', 'e', 'y'};
  System.out.println(Arrays.asList(list).indexOf('e')); // print "1"
}

int i = 0;
int count = 1;
        while ('e'!= list[i] ) {
            i++;
            count++;
        }

        System.out.println(count);

If the initial order of elements isn't really important, you could just sort the array, then binarySearch it:

import java.util.Arrays;

class masi { 
    public static void main( String[] args ) { 
        char[] list = {'m', 'e', 'y'};
        Arrays.sort(list);

        // should print 0, as e is now sorted to the beginning
        // returns negative number if the result isn't found
        System.out.println( Arrays.binarySearch(list, 'e') );
    } 
}

Alternatively, you can use Commons Lang ArrayUtils class:

int[] arr = new int{3, 5, 1, 4, 2};
int indexOfTwo = ArrayUtils.indexOf(arr, 2);

There are overloaded variants of indexOf() method for different array types.


Now it does print 1

class Masi {
    public static void main( String [] args ) {
         char [] list = { 'm', 'e', 'y' };

         // Prints 1
         System.out.println( indexOf( 'e', list ) );
    }

    private static int indexOf( char c , char [] arr ) {
        for( int i = 0 ; i < arr.length ; i++ ) {
            if( arr[i] == c ) { 
                return i;
            }
         }
         return -1;
     }
 }

Bear in mind that

"e"

is an string object literal ( which represents an string object that is )

While

'e'

Is a character literal ( which represents a character primitive datatype )

Even when

list[]

Would be valid Java ( which is not ) comparing the a character element with a string element would return false anyway.

Just use that indexOf string function and you could find any character within any alphabet ( or array of characters )


I am providing the proper method to do this one

/**
     * 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;
    }

Very Heavily Edited. I think either you want this:

class CharStorage {
    /** set offset to 1 if you want b=1, o=2, y=3 instead of b=0... */
    private final int offset=0;
    private int array[]=new int[26];

    /** Call this with up to 26 characters to initialize the array.  For 
      * instance, if you pass "boy" it will init to b=0,o=1,y=2.
      */
    void init(String s) {
        for(int i=0;i<s.length;i++)
            store(s.charAt(i)-'a' + offset,i); 
    }

    void store(char ch, int value) {
        if(ch < 'a' || ch > 'z') throw new IllegalArgumentException();
        array[ch-'a']=value;
    }

    int get(char ch) {
        if(ch < 'a' || ch > 'z') throw new IllegalArgumentException();
        return array[ch-'a'];
    }
}

(Note that you may have to adjust the init method if you want to use 1-26 instead of 0-25)

or you want this:

int getLetterPossitionInAlphabet(char c) {
    return c - 'a' + 1
}

The second is if you always want a=1, z=26. The first will let you put in a string like "qwerty" and assign q=0, w=1, e=2, r=3...


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?

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?