61

I wanted to know if there's a native method in array for Java to get the index of the table for a given value ?

Let's say my table contains these strings :

public static final String[] TYPES = {
        "Sedan",
        "Compact",
        "Roadster",
        "Minivan",
        "SUV",
        "Convertible",
        "Cargo",
        "Others"
    };

Let's say the user has to enter the type of car and that then in the background the program takes that string and get's it's position in the array.

So if the person enters : Sedan It should take the position 0 and store's it in the object of Cars created by my program ...

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Cyberflow
  • 1,255
  • 5
  • 14
  • 24

13 Answers13

204

Type in:

Arrays.asList(TYPES).indexOf("Sedan");
Devealte
  • 219
  • 3
  • 19
  • 6
    This uses the Arrays class to convert the TYPES array to a List object. The List class has a method(.indexOf) which will return the index of the passed in object (in this case a String). Nice solution if you don't mind creating the List out of the array. +1 – Craig B Nov 06 '14 at 05:55
  • 1
    The array is converted to a list which costs cpu and battery on mobile but it will perform correctly. – Gary Davies Oct 12 '16 at 08:49
  • 3
    Great, but you should comment that must import java.util.Arrays – Adexe Rivera Oct 22 '18 at 11:20
  • 2
    @GaryDavies If you care about Object/List creation in java, you are in the wrong language ... – kaiser Oct 22 '19 at 06:30
31
String carName = // insert code here
int index = -1;
for (int i=0;i<TYPES.length;i++) {
    if (TYPES[i].equals(carName)) {
        index = i;
        break;
    }
}

After this index is the array index of your car, or -1 if it doesn't exist.

Anubian Noob
  • 13,426
  • 6
  • 53
  • 75
13
for (int i = 0; i < Types.length; i++) {
    if(TYPES[i].equals(userString)){
        return i;
    }
}
return -1;//not found

You can do this too:

return Arrays.asList(Types).indexOf(userSTring);
Mohsen Kamrani
  • 7,177
  • 5
  • 42
  • 66
12

I had an array of all English words. My array has unique items. But using…

Arrays.asList(TYPES).indexOf(myString);

…always gave me indexOutOfBoundException.

So, I tried:

Arrays.asList(TYPES).lastIndexOf(myString);

And, it worked. If your arrays don't have same item twice, you can use:

Arrays.asList(TYPES).lastIndexOf(myString);
Tzar
  • 5,132
  • 4
  • 23
  • 57
suhid
  • 121
  • 1
  • 3
8

try this instead

org.apache.commons.lang.ArrayUtils.indexOf(array, value);
Wayne
  • 81
  • 1
  • 4
6

Use Arrays class to do this

Arrays.sort(TYPES);
int index = Arrays.binarySearch(TYPES, "Sedan");
Arjit
  • 3,290
  • 1
  • 17
  • 18
  • 1
    Can't `TYPES` not be sorted because it is `final`? – The Guy with The Hat Apr 18 '14 at 19:57
  • 6
    The OP wants to know the index of the string in the list in its original order. Once you sort it you will likely be returning a different index from where it was originally. – Craig B Nov 06 '14 at 05:41
  • 1
    Also regarding "final". Standard java arrays are mutable regardless of whether they are declared final. Final just means that the TYPES variable cannot have another object assigned to it. Guava has some immutable collections which might be worth looking into if you are interested. – Craig B Nov 06 '14 at 06:15
5

No built-in method. But you can implement one easily:

public static int getIndexOf(String[] strings, String item) {
    for (int i = 0; i < strings.length; i++) {
        if (item.equals(strings[i])) return i;
    }
    return -1;
}
Raphael C
  • 2,296
  • 1
  • 22
  • 22
2

There is no native indexof method in java arrays.You will need to write your own method for this.

abhishek58g
  • 145
  • 4
1

An easy way would be to iterate over the items in the array in a loop.

for (var i = 0; i < arrayLength; i++) {
 // (string) Compare the given string with myArray[i]
 // if it matches store/save i and exit the loop.
}

There would definitely be better ways but for small number of items this should be blazing fast. Btw this is javascript but same method should work in almost every programming language.

R.W
  • 530
  • 1
  • 12
  • 34
0

Try this Function :

public int indexOfArray(String input){
     for(int i=0;i<TYPES,length();i++)
       {
         if(TYPES[i].equals(input))
         {
          return i ;
         }
        }
      return -1     // if the text not found the function return -1
      }
Alaeddine
  • 1,571
  • 2
  • 22
  • 46
0

Testable mockable interafce

public interface IArrayUtility<T> {

    int find(T[] list, T item);

}

implementation

public class ArrayUtility<T> implements IArrayUtility<T> {

    @Override
    public int find(T[] array, T search) {
        if(array == null || array.length == 0 || search == null) {
            return -1;
        }

        int position = 0;

        for(T item : array) {

            if(item.equals(search)) {
                return position;
            } else {
                ++position;
            }
        }

        return -1;
    }

}

Test

@Test
public void testArrayUtilityFindForExistentItemReturnsPosition() {
    // Arrange
    String search = "bus";
    String[] array = {"car", search, "motorbike"};

    // Act
    int position = arrayUtility.find(array, search);

    // Assert
    Assert.assertEquals(position, 1);
}
Gary Davies
  • 920
  • 15
  • 12
0

Use this as a method with x being any number initially. The string y being passed in by console and v is the array to search!

public static int getIndex(int x, String y, String[]v){
    for(int m = 0; m < v.length; m++){
        if (v[m].equalsIgnoreCase(y)){
            x = m;
        }
    }
    return x;
}
CroMagnon
  • 1,218
  • 7
  • 20
  • 32
0

Refactoring the above methods and showing with the use:

private String[] languages = {"pt", "en", "es"};
private Integer indexOf(String[] arr, String str){
   for (int i = 0; i < arr.length; i++)
      if(arr[i].equals(str)) return i;
   return -1;
}
indexOf(languages, "en")