我在Java中有一个这样的Hashmap:

private Map<String, Integer> team1 = new HashMap<String, Integer>();

然后我像这样填充它:

team1.put("United", 5);

我怎么才能拿到钥匙?类似于:team1.getKey()返回“United”。


当前回答

试试这个简单的程序:

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);
   }    
}

其他回答

如果你只是需要一些简单的验证。

public String getKey(String key)
{
    if(map.containsKey(key)
    {
        return key;
    }
    return null;
}

然后你可以搜索任何键。

System.out.println( "Does this key exist? : " + getKey("United") );

试试这个简单的程序:

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);
   }    
}

您可以使用keySet()方法检索Map的所有键。现在,如果你需要的是一个给定值的键,那就完全是另一回事了Map不会帮你;你需要一个专门的数据结构,像来自Apache的公共集合的bidmap(一个允许键和值之间双向查找的映射)-还要注意几个不同的键可以映射到相同的值。

Foreach也可以使用。

team1.forEach((key, value) -> System.out.println(key));

使用函数式操作来实现更快的迭代。

team1.keySet().forEach((key) -> {
      System.out.println(key);
});