Reputation: 9437
What is the most efficient way of finding a ArrayList element according to a "subelement"?
For instance I have an ArrayList named test that is made up of these Arrays:
{a,first}
{b, second}
{c, third}
{d, fourth}
I am trying to create a method so that I can find the second element of each sub element(the array of Strings). My method would be something like:
public static String getElement(String key, ArrayList<String[]> haystack)
so calling the method
getElement("a", test)
would return the String "first". I know I could loop through the whole array and find it that way but I was wondering if there would be a more efficient way. Thanks
Upvotes: 1
Views: 2529
Reputation: 117675
You can define Pair
:
public class Pair
{
private String key;
private String string;
public Pair(String key, String string)
{
this.key = key;
this.string = string;
}
public String getKey(){return key;}
public String getString(){return string;}
}
and then use it like:
public static String getElement(String key, ArrayList<Pair> list)
for(Pair p : list)
{
if(p.getKey().equals(key)) return p.getString();
}
Upvotes: 0
Reputation: 24910
I think you might be actually looking for Map implementation.
If not, your option is to bruteforce it, which means you have to scan through the list of elements, then look at the first element in the array and if its equal, return the second element.
for ( String[] a : haystack ) {
if ( key.equals(a[0])
return a[1];
}
EDIT --
You could take the arraylist and convert it into a map by iterating over it. This would only be useful if you are given the ArrayList once and you have to repeatedly perform the "get" oepration on it.
Map<String, String> myMap = new HashMap<String, String>();
for ( String[] a : haystack )
myMap.put(a[0] , a[1]);
Once you are done with that, you can just call
myMap.get(key);
Upvotes: 5
Reputation: 88478
Please use a Map
instead of an ArrayList
for this. Or were you given a list by someone else.
If you must use a list, and the list is unsorted, and you only need to do the operation once, you can walk through the outer array.
Upvotes: 0