'find value in ArrayList<HashMap> and get the index
I have a ArrayList<HashMap<String, String>> and it looks something like this
[{code=123, name=tester, model=car1},{code=456, name=tester, model=car2},{code=789, name=tester, model=car3}]
And what I want to do is search through it to find if any model number equals car2 and get the index of the object (in this case 1) so i can print out the name. Whats the best way to do this?
Solution 1:[1]
Scan each element in your list and break when you've found your element.
int i;
for(i = 0; i < haystackList.size(); i++){
if(haystackList.get(i).get("model").equals(needle)){
// Break
}
}
if(i == haystackList.size()){
// Failure
} else {
// Success
}
Solution 2:[2]
Not exactly an efficient solution, as it can end up going through the entire ArrayList twice, but it'll get the job done.
int index;
for( HashMap m : mapList )
{
if( m.get( "model" ).equals( "car2" ) )
{
index = arrayList.indexOf( m );
break;
}
}
Solution 3:[3]
Loop through the ArrayList and check each HashMap:
for (HashMap map : arraylist) {
if ("car2".equals(map.get("model"))) {
System.out.println("index: " + arraylist.indexOf(map));
System.out.println("name: " + map.get("name"));
break;
}
}
The break was included under the assumption that only one model will be car2.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dan S |
| Solution 2 | gla3dr |
| Solution 3 |
