从Java中获取HashMap的密钥 [英] Get keys from HashMap in Java
本文介绍了从Java中获取HashMap的密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Java中有一个Hashmap,如下所示:
I have a Hashmap in Java like this:
private Map<String, Integer> team1 = new HashMap<String, Integer>();
然后我这样填写:
team1.put("United", 5);
我如何获得钥匙?类似于: team1.getKey()
返回United。
How can I get the keys? Something like: team1.getKey()
to return "United".
推荐答案
A HashMap
包含多个密钥。您可以使用 keySet()
来获取所有密钥的集合。
A HashMap
contains more than one key. You can use keySet()
to get the set of all keys.
team1.put("foo", 1);
team1.put("bar", 2);
将使用密钥<$ c存储 1
$ c>foo和 2
,密钥bar
。迭代所有键:
will store 1
with key "foo"
and 2
with key "bar"
. To iterate over all the keys:
for ( String key : team1.keySet() ) {
System.out.println( key );
}
将打印foo
和bar
。
这篇关于从Java中获取HashMap的密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文