Print all key/value pairs in a Java ConcurrentHashMap
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);
}
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));