mas*_*asb 152 java java-6 data-structures
我有一个Java中的Hashmap,如下所示:
private Map<String, Integer> team1 = new HashMap<String, Integer>();
Run Code Online (Sandbox Code Playgroud)
然后我这样填写:
team1.put("United", 5);
Run Code Online (Sandbox Code Playgroud)
我怎样才能获得钥匙?像:team1.getKey()回归"联合国".
Mat*_*teo 293
A HashMap包含多个键.您可以使用keySet()获取所有键的集合.
team1.put("foo", 1);
team1.put("bar", 2);
Run Code Online (Sandbox Code Playgroud)
将存储1密钥"foo"和2密钥"bar".迭代所有键:
for ( String key : team1.keySet() ) {
System.out.println( key );
}
Run Code Online (Sandbox Code Playgroud)
将打印"foo"和"bar".
jam*_*iss 46
如果你知道索引,这是可行的,至少在理论上是这样的:
System.out.println(team1.keySet().toArray()[0]);
Run Code Online (Sandbox Code Playgroud)
keySet() 返回一个集合,因此您将该集合转换为数组.
当然,问题在于一套不承诺保留您的订单.如果你的HashMap中只有一个项目,那么你很好,但是如果你有更多,那么最好循环遍历地图,就像其他答案一样.
Fab*_* F. 23
检查一下.
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> getKey(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> getKeys(Integer value){
return team1
.entrySet()
.stream()
.filter(e -> Objects.equals(e.getValue(), value))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)
更"通用",尽可能安全
/**
* 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> getKey(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());
}
Run Code Online (Sandbox Code Playgroud)
或者如果您使用的是JDK7.
private String getKey(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> getKeys(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;
}
Run Code Online (Sandbox Code Playgroud)
您可以Map使用该方法检索所有密钥keySet().现在,如果您需要的是获得一个具有价值的钥匙,这是一个完全不同的问题,并不会帮助您; 你需要一个专门的数据结构,比如(一个允许在键和值之间进行双向查找的映射)来自Apache的Commons Collections - 同时要注意几个不同的键可以映射到相同的值.MapBidiMap
小智 5
使用函数运算来加快迭代速度。
team1.keySet().forEach((key) -> {
System.out.println(key);
});
Run Code Online (Sandbox Code Playgroud)