Reputation: 401
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
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
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
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