Nisal Malinda Livera
Nisal Malinda Livera

Reputation: 401

How to Iterate through the Android ArrayList and get the Index

I have this two ArrayLists. I need to iterate through the stationNames Array and get the index. Then return the value of the same index of stationIDs array. How do i achieve this? Please help me. The existing solutions on stackoverflow didn't work on this. I am new to android development.

When i iterate through the Array like the following code it give an error saying Array type expected; found: java.util.ArrayList<java.lang.String>

ArrayList<String> stationNames = new ArrayList<String>();
ArrayList<String> stationIDs = new ArrayList<String>();

stationName = "Hello"

int index = -1;
try {
    for (int i = 0; i < stationNames.length; i++) {
        if (stationNames[i].equals(stationName)) {
            index = i;
            break;
        }
    }
}
catch (Exception e){
    Log.d("Excetion!",e.getLocalizedMessage());
}
return stationIDs[index];

Upvotes: 1

Views: 5645

Answers (3)

Nisal Malinda Livera
Nisal Malinda Livera

Reputation: 401

Without all the hazzle of try catches and for loops. I could do the same task with one line of code, like following...

int output = stationIDs.get(stationNames.indexOf(stationName));

Thank you all for your help!

Upvotes: 1

riaz hasan
riaz hasan

Reputation: 1155

Just use indexOf method of the ArrayList object.

ArrayList<String> stationNames = new ArrayList<String>();
ArrayList<String> stationIDs = new ArrayList<String>();

String stationName = "Hello"

int index = stationNames. indexOf(stationName);

if(index!=-1){
 String value= stationIDs[index];
}

Upvotes: -1

Aman Grover
Aman Grover

Reputation: 45

stationNames here is not an array , but an ArrayList. So, you cannot use .length on it, use .size() :

Even simpler to do :

return stationNames.indexOf(stationName);

if it is found in the list will return its position or -1 if not.

Upvotes: 3

Related Questions