1

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

2
  • Why are you using an arrayList, have you looked into using a hashmap? Commented Jul 13, 2011 at 20:55
  • Do you call that method more than once? Or is it a one-shot operation? Commented Jul 13, 2011 at 21:00

3 Answers 3

5

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

I was given an ArrayList, is there a way to transform this ArrayList to a Map?
0

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.