问题
我有一个Java中的Hashmap,如下所示:
private Map<String, Integer> team1 = new HashMap<String, Integer>();
然后我这样填写:
team1.put("United", 5);
我怎样才能拿到钥匙?类似于:team1.getKey()
返回"United"。
#1 热门回答(229 赞)
AHashMap
包含多个密钥。你可以使用keySet()
获取所有密钥的集合。
team1.put("foo", 1);
team1.put("bar", 2);
将key250294247与key"foo"
和2
与key"bar"
一起存储。迭代所有键:
for ( String key : team1.keySet() ) {
System.out.println( key );
}
将打印"foo"
和"bar"
。
#2 热门回答(29 赞)
这是可行的,至少在理论上,如果你知道索引,则为:
System.out.println(team1.keySet().toArray()[0]);
keySet()
返回一个列表,因此你将列表转换为数组。
当然,问题在于一套不承诺保留你的订单。如果你的HashMap中只有一个项目,那么你很好,但是如果你有更多,那么最好循环遍历 Map ,就像其他答案一样。
#3 热门回答(19 赞)
检查一下。
http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
假设你为每个键设置了不同的值,你可以执行以下操作:
private String getKey(Integer value){
for(String key : team1.keySet()){
if(team1.get(key).equals(value)){
return key; //return the first found
}
}
return null;
}
或者,如果你不能假设每个键具有不同的值:
private List<String> getKeys(Integer value){
List<String> keys = new ArrayList<String>();
for(String key : team1.keySet()){
if(team1.get(key).equals(value)){
keys.add(key);
}
}
return keys;
}
或者使用JDK8
private Optional<String> getKey(Integer value){
return team1
.entrySet()
.stream()
.filter(e -> e.getValue().equals(value))
.map(Map.Entry::getKey)
.findFirst();
}
private List<String> getKeys(Integer value){
return team1
.entrySet()
.stream()
.filter(e -> e.getValue().equals(value))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}