Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the index of an array item based on the value

Tags:

java

android

I have a string array defined in arrays.xml that references two strings in strings.xml:

<string-array name="my_options">
  <item>@string/my_string_one</item>
  <item>@string/my_string_two</item>
</string-array>

<string name="my_string_one">Value 1</string>
<string name="my_string_two">Value 2</string>

I need to get the position of an item in the array, based on the value of the string. I.e string "Value 2" has an index of 1. I can obviously just hard code the positional values (0, 1, etc.), but it will break if the order of the strings is changed. I want the code to be positionally independent. The following works:

int value = Arrays.asList((getResources().getStringArray(R.array.my_options))).indexOf(getString(R.string.my_string_one));

Is there a more compact, simpler way to do this?

like image 529
Craig Avatar asked Feb 04 '13 22:02

Craig


People also ask

How do you find the index of an array based on value?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.

Can you use indexOf for an array of objects?

The Array. indexOf() method returns the index of the first matching item in an array (or -1 if it doesn't exist). var wizards = ['Gandalf', 'Radagast', 'Saruman', 'Alatar']; // Returns 1 wizards.

How do you find the index of an object in an array in TypeScript?

The Array. indexOf() is an inbuilt TypeScript function which is used to find the index of the first occurrence of the search element provided as the argument to the function.

How do you find the index of a value in an array in Python?

The list index() method helps you to find the index of the given element. This is the easiest and straightforward way to get the index. The list index() method returns the index of the given element.


1 Answers

The code you show in your question is basically what you need to do.

However, you could refactor it somewhat to make it more readable: Refactor Arrays.asList((getResources().getStringArray(R.array.my_options))) into a List (i don't know how your app's code looks like, but you may be able to store this List as a instance field or even as a static (class) field).

static List<String> myOptions;

.... 
    if (myOptions == null) {
        myOptions = Arrays.asList((getResources().getStringArray(R.array.my_options)));
    }

...

    int value = myOptions.indexOf(getString(R.string.my_string_one));
like image 51
Streets Of Boston Avatar answered Sep 20 '22 19:09

Streets Of Boston