ตรวจสอบสิ่งนี้
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());
}
เพิ่มเติม "ทั่วไป" และปลอดภัยที่สุด
/**
* 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());
}
หรือถ้าคุณอยู่บน 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;
}
team1.getKey()
หาก: (1) แผนที่ว่างเปล่าหรือ (2) หากมีหลายคีย์