如何从哈希映射返回键列表?
我目前正在尝试制作一个将动词结合成西班牙语的程序。我创建了一个哈希表,其中包含一个键和对象 Verb 的实例。键是一个具有动词不定式形式的字符串(例如“hablar”)。这是我到目前为止的哈希映射代码:
public class VerbHashMap {
HashMap<String, Verb> verbHashMap;
public VerbHashMap(){
verbHashMap = new HashMap();
}
}
HashMap 中每个动词的键都基于动词的不定式形式。例如,字符串“hablar”是西班牙语动词的键。 Verb 类有一个名为 getInfinitive() 的方法,它返回一个包含动词不定式形式的字符串。
public boolean addVerb(Verb verb){
if(verbHashMap.containsValue(verb.getInfinitive()){
return false;
}
else{
verbHashMap.put(verb.getInfinitive(), verb);
return true;
}
}
问题是创建一个按字母顺序返回哈希映射中所有动词列表的方法的最有效方法是什么?我应该让该方法返回一个包含哈希映射中所有对象的键的 ArrayList 吗?或者有没有更有效的方法来解决这个问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用
keySet()
方法返回包含Map
的所有键的集合。如果您想保持地图有序,可以使用 <代码>TreeMap。
Use the
keySet()
method to return a set with all the keys of aMap
.If you want to keep your Map ordered you can use a
TreeMap
.使用
map.keySet()
,您可以获得一组键。然后通过以下方式将此集合转换为List
:然后使用
l.get(int)
方法访问密钥。PS:- source- 转换 Set 的最简洁方法< ;字符串>到列表
Using
map.keySet()
, you can get a set of keys. Then convert this set intoList
by:And then use
l.get(int)
method to access keys.PS:- source- Most concise way to convert a Set<String> to a List<String>
这样就可以了。
This is will do just fine.
将返回您所有的钥匙。如果你想对键进行排序,你可以考虑使用 TreeMap
will return you all the keys. If you want the keys to be sorted, you might consider a TreeMap
从 Java 8 开始:
Since Java 8:
您可以通过 keyat 方法获取密钥,并且必须传递索引,然后它将返回该特定索引处的密钥。这个循环将获得所有的密钥
you can get key by method keyat and you have to pass the index then it will return key at that particular index. this loop will get all the key