I have several Lists of Strings. Each list represents a category. I am trying to find which category a specific string is in. I could only think of two ways to do this:
-
Iterate through categories and return the first category that contains it.
-
Create a running hashmap of strings and their categories.
Which one is faster/more efficient or is there a better way than the methods listed above to find which category the string is in?
So, looking up something in a hash map is constant time (amortized) whereas iterating through every list is m*n time, where m is the list length and n is the number of lists. Go with the hash map, definitely.
Alternatively, make every string an object that contains the category.