Get keys from HashMap in Java

后端 未结 14 2635
野的像风
野的像风 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 07:49
    private Map<String, Integer> _map= new HashMap<String, Integer>();
    Iterator<Map.Entry<String,Integer>> itr=  _map.entrySet().iterator();
                    //please check 
                    while(itr.hasNext())
                    {
                        System.out.println("key of : "+itr.next().getKey()+" value of      Map"+itr.next().getValue());
                    }
    
    0 讨论(0)
  • 2020-12-04 07:54

    If you just need something simple and more of a verification.

    public String getKey(String key)
    {
        if(map.containsKey(key)
        {
            return key;
        }
        return null;
    }
    

    Then you can search for any key.

    System.out.println( "Does this key exist? : " + getKey("United") );
    
    0 讨论(0)
  • 2020-12-04 07:55

    Use functional operation for faster iteration.

    team1.keySet().forEach((key) -> { System.out.println(key); });

    0 讨论(0)
  • 2020-12-04 07:59

    A HashMap contains more than one key. You can use keySet() to get the set of all keys.

    team1.put("foo", 1);
    team1.put("bar", 2);
    

    will store 1 with key "foo" and 2 with key "bar". To iterate over all the keys:

    for ( String key : team1.keySet() ) {
        System.out.println( key );
    }
    

    will print "foo" and "bar".

    0 讨论(0)
  • 2020-12-04 07:59

    This is doable, at least in theory, if you know the index:

    System.out.println(team1.keySet().toArray()[0]);
    

    keySet() returns a set, so you convert the set to an array.

    The problem, of course, is that a set doesn't promise to keep your order. If you only have one item in your HashMap, you're good, but if you have more than that, it's best to loop over the map, as other answers have done.

    0 讨论(0)
  • 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<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());
    }
    

    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 <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());
    }
    

    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<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;
    }
    
    0 讨论(0)
提交回复
热议问题