我在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”。
当前回答
一个解决方案是,如果你知道键的位置,将键转换为一个String数组,并返回该位置的值:
public String getKey(int pos, Map map) {
String[] keys = (String[]) map.keySet().toArray(new String[0]);
return keys[pos];
}
其他回答
一个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”。
private Map<String, Integer> _map= new HashMap<String, Integer>();
Iterator<Map.Entry<String,Integer>> itr= _map.entrySet().iterator();
//please check
while(itr.hasNext())
{
System.out.println("key of : "+itr.next().getKey()+" value of Map"+itr.next().getValue());
}
当你想要获得参数(United)的值(5),你也可以考虑使用双向映射(例如,由Guava: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/BiMap.html提供)。
Foreach也可以使用。
team1.forEach((key, value) -> System.out.println(key));
试试这个简单的程序:
public class HashMapGetKey {
public static void main(String args[]) {
// create hash map
HashMap map = new HashMap();
// populate hash map
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
// get keyset value from map
Set keyset=map.keySet();
// check key set values
System.out.println("Key set values are: " + keyset);
}
}