Print all key/value pairs in a Java ConcurrentHashMap

前端 未结 6 710
清歌不尽
清歌不尽 2021-02-02 17:40

I am trying to simply print all key/value pair(s) in a ConcurrentHashMap.

I found this code online that I thought would do it, but it seems to be getting information ab

6条回答
  •  囚心锁ツ
    2021-02-02 17:51

    Work 100% sure try this code for the get all hashmap key and value

    static HashMap map = new HashMap<>();
    
    map.put("one"  " a " );
    map.put("two"  " b " );
    map.put("three"  " c " );
    map.put("four"  " d " );
    

    just call this method whenever you want to show the HashMap value

     private void ShowHashMapValue() {
    
            /**
             * get the Set Of keys from HashMap
             */
            Set setOfKeys = map.keySet();
    
    /**
     * get the Iterator instance from Set
     */
            Iterator iterator = setOfKeys.iterator();
    
    /**
     * Loop the iterator until we reach the last element of the HashMap
     */
            while (iterator.hasNext()) {
    /**
     * next() method returns the next key from Iterator instance.
     * return type of next() method is Object so we need to do DownCasting to String
     */
                String key = (String) iterator.next();
    
    /**
     * once we know the 'key', we can get the value from the HashMap
     * by calling get() method
     */
                String value = map.get(key);
    
                System.out.println("Key: " + key + ", Value: " + value);
            }
        } 
    

提交回复
热议问题