[java] Print all key/value pairs in a Java ConcurrentHashMap

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 about the buckets/hashcode. Actually to be honest the output it quite strange, its possible my program is incorrect, but I first want to make sure this part is what I want to be using.

for (Entry<StringBuilder, Integer> entry : wordCountMap.entrySet()) {
    String key = entry.getKey().toString();
    Integer value = entry.getValue();
    System.out.println("key, " + key + " value " + value);
}

This gives output for about 10 different keys, with counts that seem to be the sum of the number of total inserts into the map.

This question is related to java collections hashmap concurrenthashmap

The answer is


  //best and simple way to show keys and values

    //initialize map
    Map<Integer, String> map = new HashMap<Integer, String>();

   //Add some values
    map.put(1, "Hi");
    map.put(2, "Hello");

    // iterate map using entryset in for loop
    for(Entry<Integer, String> entry : map.entrySet())
    {   //print keys and values
         System.out.println(entry.getKey() + " : " +entry.getValue());
    }

   //Result : 
    1 : Hi
    2 : Hello

You can do something like

Iterator iterator = map.keySet().iterator();

while (iterator.hasNext()) {
   String key = iterator.next().toString();
   Integer value = map.get(key);

   System.out.println(key + " " + value);
}

Here 'map' is your concurrent HashMap.


The HashMap has forEach as part of its structure. You can use that with a lambda expression to print out the contents in a one liner such as:

map.forEach((k,v)-> System.out.println(k+", "+v));

or

map.forEach((k,v)-> System.out.println("key: "+k+", value: "+v));

The ConcurrentHashMap is very similar to the HashMap class, except that ConcurrentHashMap offers internally maintained concurrency. It means you do not need to have synchronized blocks when accessing ConcurrentHashMap in multithreaded application.

To get all key-value pairs in ConcurrentHashMap, below code which is similar to your code works perfectly:

//Initialize ConcurrentHashMap instance
ConcurrentHashMap<String, Integer> m = new ConcurrentHashMap<String, Integer>();

//Print all values stored in ConcurrentHashMap instance
for each (Entry<String, Integer> e : m.entrySet()) {
  System.out.println(e.getKey()+"="+e.getValue());
}

Above code is reasonably valid in multi-threaded environment in your application. The reason, I am saying 'reasonably valid' is that, above code yet provides thread safety, still it can decrease the performance of application.

Hope this helps you.


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

static HashMap<String, String> 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);
        }
    } 

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to collections

Kotlin's List missing "add", "remove", Map missing "put", etc? How to unset (remove) a collection element after fetching it? How can I get a List from some class properties with Java 8 Stream? Java 8 stream map to list of keys sorted by values How to convert String into Hashmap in java How can I turn a List of Lists into a List in Java 8? MongoDB Show all contents from all collections Get nth character of a string in Swift programming language Java 8 Distinct by property Is there a typescript List<> and/or Map<> class/library?

Examples related to hashmap

How to split a string in two and store it in a field Printing a java map Map<String, Object> - How? Hashmap with Streams in Java 8 Streams to collect value of Map How to convert String into Hashmap in java Convert object array to hash map, indexed by an attribute value of the Object HashMap - getting First Key value The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files Sort Go map values by keys Print all key/value pairs in a Java ConcurrentHashMap creating Hashmap from a JSON String

Examples related to concurrenthashmap

Print all key/value pairs in a Java ConcurrentHashMap Is iterating ConcurrentHashMap values thread safe?