我在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];
}
其他回答
如果你只是需要一些简单的验证。
public String getKey(String key)
{
if(map.containsKey(key)
{
return key;
}
return null;
}
然后你可以搜索任何键。
System.out.println( "Does this key exist? : " + getKey("United") );
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());
}
一个解决方案是,如果你知道键的位置,将键转换为一个String数组,并返回该位置的值:
public String getKey(int pos, Map map) {
String[] keys = (String[]) map.keySet().toArray(new String[0]);
return keys[pos];
}
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()方法,该方法存在于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]