Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

java - How to return a list of keys from a Hash Map?

I'm currently trying to make a program that conjugates verbs into Spanish. I've created a Hash Table that contains a key and an instantiation of the object Verb. The key is a string that has the infinitive form of the verb (for example, "hablar"). This is the code that I have so far for the hash map:

public class VerbHashMap {

    HashMap<String, Verb> verbHashMap;

    public VerbHashMap(){
        verbHashMap = new HashMap();
    }   
}

Each verb's key in the HashMap is based on the infinitive form of the verb. For example, the string "hablar" is the key for a Spanish verb. The class Verb has a method called getInfinitive() which returns a string that contains the infinitive form of the verb.

public boolean addVerb(Verb verb){
    if(verbHashMap.containsValue(verb.getInfinitive()){
        return false;
    }
    else{
        verbHashMap.put(verb.getInfinitive(), verb);
        return true;
    }
}

The question is what is the most efficient way to create a method that returns a list of all the verbs in the Hash Map in alphabetical order? Should I have the method return an ArrayList which includes the keys of all the objects in the Hash Map? Or is there a much more efficient way to go about this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the keySet() method to return a set with all the keys of a Map.

If you want to keep your Map ordered you can use a TreeMap.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...