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.
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.
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.
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 ).
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With