Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 431
DanGordon Avatar asked Mar 26 '14 13:03

DanGordon


People also ask

How do you get keys in ConcurrentHashMap?

ConcurrentHashMap keys() method in Java with ExamplesThe keys() method of ConcurrentHashMap class in Java is used to get the enumeration of the keys present in the hashmap. Parameters: The method does not take any parameters. Return value: The method returns an enumeration of the keys of the ConcurrentHashMap.

How do I print a key value pair on a map?

Using toString() For displaying all keys or values present on the map, we can simply print the string representation of keySet() and values() , respectively. That's all about printing out all keys and values from a Map in Java.

What are the changes in ConcurrentHashMap in Java 8?

Creates a new, empty map with an initial table size based on the given number of elements ( initialCapacity ), table density ( loadFactor ), and number of concurrently updating threads ( concurrencyLevel ).


1 Answers

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);
}
like image 91
Slimu Avatar answered Oct 23 '22 11:10

Slimu