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

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

然后我像这样填充它:

team1.put("United", 5);

我怎么才能拿到钥匙?类似于:team1.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());
                }

其他回答

一个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”。

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

我要做的非常简单,但浪费内存的是将值映射到一个键,并相反地将键映射到一个值,这样做:

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

使用<Object, Object>很重要,这样你就可以像这样映射key:Value和Value: key

team1。(“联合”,5);

team1。把(5,“联合”);

如果你使用team1。get("United") = 5和team1。get(5) = "United"

但如果你对其中一个对象使用特定的方法,我会更好,如果你做另一张地图:

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

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

然后

team1。(“联合”,5);

team1Keys。把(5,“联合”);

记住,保持简单。

这是可行的,至少在理论上,如果你知道索引:

System.out.println(team1.keySet().toArray()[0]);

keySet()返回一个集合,因此您可以将集合转换为一个数组。

当然,问题是一套并不能保证保证你的订单。如果HashMap中只有一个项,那么就很好,但如果有更多项,最好像其他答案那样循环遍历该映射。

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

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