1

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.

1
  • When your mapping is fixed then you can think about using enum. There you can define your keys and each can have getter for your mapping. Commented Apr 29, 2012 at 9:23

2 Answers 2

3

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:

HashMap map = new HashMap();
map.put("dog", "animal");
map.put("chair", "furniture");
map.put("cat", "animal");

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Exactly, plus making category enumereation would be nice
map.get("chair") returns "cat" ?
0

You can change your enum like the following:

public enum Things{
    _ANIMAL("Dog"), _FURNITURE("Animal"); 
    private String description;
    Things(String description){
        this.description= description;
    }
    public String toString(){
        return description;
    }
};

Whenever you want to retrieve the string representation of your enum, just call toString

Example:

Things._ANIMAL.toString() will output "Dog"

2 Comments

I think you should invert eum values and descrption for your code to match the question: _Dog("Animal"), _Chair("FURNITURE"); There could be more instance for category. Also, I thinks maybe better to use a second enum to represent items.
@AndreaParodi Thanks for your comment. This _Dog("Animal") does not sound right as in the OP's question, _Animal is an enum not a string

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.