[java] How to find index of STRING array in Java from a given value?

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 ...

This question is related to java arrays string position

The answer is


Type in:

Arrays.asList(TYPES).indexOf("Sedan");

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

Use Arrays class to do this

Arrays.sort(TYPES);
int index = Arrays.binarySearch(TYPES, "Sedan");

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

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.


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")

try this instead

org.apache.commons.lang.ArrayUtils.indexOf(array, value);

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

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


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

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
      }

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

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 string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to position

How does the "position: sticky;" property work? React Native absolute positioning horizontal centre RecyclerView - Get view at particular position RecyclerView - How to smooth scroll to top of item on a certain position? How to find index of STRING array in Java from a given value? Insert node at a certain position in a linked list C++ How to position the Button exactly in CSS Float a DIV on top of another DIV Iframe positioning css - position div to bottom of containing div