我在Java中有一个这样的Hashmap:
private Map<String, Integer> team1 = new HashMap<String, Integer>();
然后我像这样填充它:
team1.put("United", 5);
我怎么才能拿到钥匙?类似于:team1.getKey()返回“United”。
我在Java中有一个这样的Hashmap:
private Map<String, Integer> team1 = new HashMap<String, Integer>();
然后我像这样填充它:
team1.put("United", 5);
我怎么才能拿到钥匙?类似于:team1.getKey()返回“United”。
当前回答
获取Key及其值
e.g
private Map<String, Integer> team1 = new HashMap<String, Integer>();
team1.put("United", 5);
team1.put("Barcelona", 6);
for (String key:team1.keySet()){
System.out.println("Key:" + key +" Value:" + team1.get(key)+" Count:"+Collections.frequency(team1, key));// Get Key and value and count
}
将打印:键:联合值:5 值:6
其他回答
要在HashMap中获取键,我们有keySet()方法,该方法存在于java.util.Hashmap包中。 例:
Map<String,String> map = new Hashmap<String,String>();
map.put("key1","value1");
map.put("key2","value2");
// Now to get keys we can use keySet() on map object
Set<String> keys = map.keySet();
现在键将有你所有的键在地图可用。 例:[key1, key2]
public class MyHashMapKeys {
public static void main(String a[]){
HashMap<String, String> hm = new HashMap<String, String>();
//add key-value pair to hashmap
hm.put("first", "FIRST INSERTED");
hm.put("second", "SECOND INSERTED");
hm.put("third","THIRD INSERTED");
System.out.println(hm);
Set<String> keys = hm.keySet();
for(String key: keys){
System.out.println(key);
}
}
}
一个HashMap包含多个键。您可以使用keySet()来获取所有键的集合。
team1.put("foo", 1);
team1.put("bar", 2);
将存储1,键“foo”和2,键“bar”。遍历所有键:
for ( String key : team1.keySet() ) {
System.out.println( key );
}
将打印“foo”和“bar”。
这是可行的,至少在理论上,如果你知道索引:
System.out.println(team1.keySet().toArray()[0]);
keySet()返回一个集合,因此您可以将集合转换为一个数组。
当然,问题是一套并不能保证保证你的订单。如果HashMap中只有一个项,那么就很好,但如果有更多项,最好像其他答案那样循环遍历该映射。
当你想要获得参数(United)的值(5),你也可以考虑使用双向映射(例如,由Guava: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/BiMap.html提供)。