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

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

然后我像这样填充它:

team1.put("United", 5);

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


当前回答

一个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());
                }

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

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

然后你可以搜索任何键。

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

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

team1.keySet().forEach((key) -> {
      System.out.println(key);
});
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);
        }
    }
}

检查这个。

https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html

(使用java.util.Objects.equals,因为HashMap可以包含null)

使用JDK8 +

/**
 * Find any key matching a value.
 *
 * @param value The value to be matched. Can be null.
 * @return Any key matching the value in the team.
 */
private Optional<String> findKey(Integer value){
    return team1
        .entrySet()
        .stream()
        .filter(e -> Objects.equals(e.getValue(), value))
        .map(Map.Entry::getKey)
        .findAny();
}

/**
 * Find all keys matching a value.
 *
 * @param value The value to be matched. Can be null.
 * @return all keys matching the value in the team.
 */
private List<String> findKeys(Integer value){
    return team1
        .entrySet()
        .stream()
        .filter(e -> Objects.equals(e.getValue(), value))
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());
}

更“通用”且尽可能安全

/**
 * Find any key matching the value, in the given map.
 *
 * @param mapOrNull Any map, null is considered a valid value.
 * @param value     The value to be searched.
 * @param <K>       Type of the key.
 * @param <T>       Type of the value.
 * @return An optional containing a key, if found.
 */
public static <K, T> Optional<K> findKey(Map<K, T> mapOrNull, T value) {
    return Optional.ofNullable(mapOrNull).flatMap(map -> map.entrySet()
            .stream()
            .filter(e -> Objects.equals(e.getValue(), value))
            .map(Map.Entry::getKey)
            .findAny());
}

或者如果您在JDK7上。

private String findKey(Integer value){
    for(String key : team1.keySet()){
        if(Objects.equals(team1.get(key), value)){
            return key; //return the first found
        }
    }
    return null;
}

private List<String> findKeys(Integer value){
   List<String> keys = new ArrayList<String>();
   for(String key : team1.keySet()){
        if(Objects.equals(team1.get(key), value)){
             keys.add(key);
      }
   }
   return keys;
}