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

364,591

Solution 1

In this case, you could create e new String from your array of chars and then do an indeoxOf("e") on that String:

System.out.println(new String(list).indexOf("e")); 

But in other cases of primitive data types, you'll have to iterate over it.

Solution 2

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.

Solution 3

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.

Solution 4

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

Solution 5

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;
  }
}
Share:
364,591
Admin
Author by

Admin

Updated on July 05, 2022

Comments

  • Admin
    Admin almost 2 years

    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?

  • Rich
    Rich over 14 years
    I very much doubt there is a list type you can build an array from. If there is, naming conventions are gravely violated.
  • skaffman
    skaffman over 14 years
    List defineas a toArray method
  • Michal aka Miki
    Michal aka Miki over 14 years
    I need to have alphabets in the array like: a -> 1, b -> 2,..., z -> 26. - I am coding just for fun, not for homework assignment.
  • Michal aka Miki
    Michal aka Miki over 14 years
    Your solution suggests me that I need to have 26 hashMap commands. Is there any way of combining the hashmaps commands?
  • Rich
    Rich over 14 years
    That was a reply to aperkins who apparently gave me a downvote for my statement that list[] == "e" was invalid syntax. For the [] to work, list has to be a type, not a variable. That's what I meant with "list type to build an array from". Sorry for the misunderstanding.
  • Michal aka Miki
    Michal aka Miki over 14 years
    The order matters in my case. My example is more simple than the problem which I have currently in hand. I have 26 letters actually in the list from a, b, ... to z.
  • Bill K
    Bill K over 14 years
    Hey, if you just want to know if a is 1, b is 2, just use "charValue-'a'+1"! I thought you wanted to actually have different values, or store things in buckets.
  • Bogdan
    Bogdan over 9 years
    This is the best way to do it. If you don't have apache in your project, add it. Another way is to use java.util.Arrays.binarySearch but it needs a sorted array, so not always useful.
  • 4castle
    4castle over 7 years
    Don't convert to an ArrayList, and don't call list.clear(). Those are iterating the array 2 extra times.
  • Gili Ariel
    Gili Ariel almost 4 years
    Can you also write here the full implementation to add to the project?
  • Nico Haase
    Nico Haase over 3 years
    Please add some explanation to your answer such that others can learn from it
  • Ali Ali
    Ali Ali over 3 years
    Your code will count how many times the 'e' char found in the string, not giving the index.
  • Arun Joseph
    Arun Joseph over 2 years
    Be careful, this will only work of char Array as the length of each character will be 1.