Get keys from HashMap in Java

后端 未结 14 2673
野的像风
野的像风 2020-12-04 07:03

I have a Hashmap in Java like this:

private Map team1 = new HashMap();

Then I fill it like th

14条回答
  •  情书的邮戳
    2020-12-04 08:00

    Check this.

    https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html

    (Use java.util.Objects.equals because HashMap can contain null)

    Using 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 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 getKeys(Integer value){
        return team1
            .entrySet()
            .stream()
            .filter(e -> Objects.equals(e.getValue(), value))
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());
    }
    

    More "generic" and as safe as 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        Type of the key.
     * @param        Type of the value.
     * @return An optional containing a key, if found.
     */
    public static  Optional getKey(Map mapOrNull, T value) {
        return Optional.ofNullable(mapOrNull).flatMap(map -> map.entrySet()
                .stream()
                .filter(e -> Objects.equals(e.getValue(), value))
                .map(Map.Entry::getKey)
                .findAny());
    }
    

    Or if you are on 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 getKeys(Integer value){
       List keys = new ArrayList();
       for(String key : team1.keySet()){
            if(Objects.equals(team1.get(key), value)){
                 keys.add(key);
          }
       }
       return keys;
    }
    

提交回复
热议问题