简体   繁体   中英

Mapping data structure in Java

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))?

PS 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:

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM