Regarde ça.
https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
(Utilisez java.util.Objects.equals
car HashMap peut contenir null
)
Utilisation de 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());
}
Plus « générique » et aussi sûr que possible
/**
* 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());
}
Ou si vous êtes sur 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;
}