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
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.
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.
Once you are done with that, you can just call