I have to devise a function that will take as input a keyword and will output a category id.
Ex:
f('dog') returns _ANIMAL
f('chair') returns _FURNITURE
I already have the mapping and I could just iterate over the tag array each time, but I have a feeling this is not the best solution.
Is there a special data structure (I’m thinking of ternary search trees) in the Java libraries for this specific task? Should I just use HashMap (or maybe Set (since there are few categories))?
P.S. This mapping is fixed, I do not need to add or remove elements from it once it is built.
If I understand you correctly, then HashMap sounds like exactly what you want. You wouldn’t want to iterate through an entire array each time, because with many function calls and/or a large array your program would wind up running slowly. With a HashMap, pulling a value (your category) from a key (your keyword) happens more or less immediately, in constant time.
You can build the map like this:
And then
map.get("dog")returns “animal”,map.get("chair")returns “furniture”.As others have indicated, enums would work well (and a tiny bit faster) for this too—with the caveat that they’re fixed at compile time and thus cannot be changed during execution.