15

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.

4
  • 1
    Looks fine to me, apart from a double semicolon on the first line in your loop. As an aside; why do you use StringBuilder as a key instead of String? I do not suppose you are updating the key after insertion, so you only end up calling .toString() every time you want to do something with the key. Commented Mar 26, 2014 at 13:55
  • The reason why is that I use StringBuilder to build a string in each thread (and it does that thousands of times). If I were to append a string, I would run out of memory (because Strings are immutable). Since I do thousands of puts on each thread, I didn't want to waste memory converting each Stringbuilder into a string before insertion.
    – DanGordon
    Commented Mar 26, 2014 at 14:47
  • I understand you want to use StringBuilder in cases where a lot of appending happens, I was not saying you should use String to replace it. I only suggested using String as the keys of your map by calling .toString() on StringBuilder when you put an entry in your map, instead of having to call .toString() each time you retrieve an entry. Commented Mar 26, 2014 at 14:51
  • So I've tried that, and performance seems to go way down. About 2gbs into my file the program seems to slow down dramatically. I'm not sure if its because of garbage collection, or just the put takes 10x longer as the map size increases.
    – DanGordon
    Commented Mar 26, 2014 at 14:59

6 Answers 6

34

I tested your code and works properly. I've added a small demo with another way to print all the data in the map:

ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);

for (String key : map.keySet()) {
    System.out.println(key + " " + map.get(key));
}

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    String key = entry.getKey().toString();
    Integer value = entry.getValue();
    System.out.println("key, " + key + " value " + value);
}
1
  • If you are using Java 8, I suggest using Rick Il Grande's answer below. It is concise and utilizes the forEach available to collections in Java 8.
    – DanGordon
    Commented Apr 5, 2018 at 17:17
23

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));
0
6

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.

4
  //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
0

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.

3
  • To be fair, he already has the loop you give as an answer (using entrySet(), getKey(), getValue()). You just squeeze it on 1 line :) Commented Mar 26, 2014 at 13:57
  • Does it matter that I am using StringBuilder?
    – DanGordon
    Commented Mar 26, 2014 at 14:30
  • I've changed my map to <Integer [], Integer>. When I do println, I get something like this back: @2d51e135 How do I get the actual value?
    – DanGordon
    Commented Mar 26, 2014 at 18:05
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.