如何从哈希表中返回键列表? [英] How to return a list of keys from a Hash Map?
问题描述
我目前正在尝试制作一个将动词连接到西班牙语的程序。我创建了一个包含对象动词的键和实例的哈希表。关键是具有动词不定式形式的字符串(例如hablar)。这是我到目前为止使用的哈希映射的代码:
public class VerbHashMap {
HashMap< String,Verb> verbHashMap;
public VerbHashMap(){
verbHashMap = new HashMap();
$ b HashMap中的每个动词的关键词都基于不定式动词的形式。例如,字符串hablar是西班牙语动词的关键。类动词有一个名为getInfinitive()的方法,该方法返回一个包含动词不定式形式的字符串。
public boolean addVerb (动词动词){
if(verbHashMap.containsValue(verb.getInfinitive()){
return false;
}
else {
verbHashMap.put(verb。
返回true;
} 问题是创建一个方法的最有效方法是按照字母顺序返回哈希表中的所有动词的列表?我应该让该方法返回一个包含所有对象的关键字的ArrayList哈希映射?或者是否有更有效的方法来解决这个问题? 使用 keySet
使用 keySet ()
方法返回一个包含 Map
的所有键的集合。
如果你想保持你的地图排序,你可以使用 TreeMap
。
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?
解决方案 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
.
这篇关于如何从哈希表中返回键列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!