问题描述
我试图在ConcurrentHashMap中打印所有的键/值对。
我在网上发现了这个代码,我认为它会这样做,但它似乎获取有关桶/散列码的信息。其实老实说输出它很奇怪,它可能我的程序是不正确的,但我首先要确定这部分是我想要使用的。
<$ p $ (Entry< StringBuilder,Integer> entry:wordCountMap.entrySet()){
String key = entry.getKey()。toString();
整数值= entry.getValue();
System.out.println(key,+ key +value+ value);
$ b $ p
$ b
这给出了大约10个不同键的输出,计数似乎是总和插入到地图中的总数。
我测试了你的代码并正常工作。我添加了一个小样本,以另一种方式打印地图中的所有数据:
ConcurrentHashMap< String,Integer> map = new ConcurrentHashMap< String,Integer>();
map.put(A,1);
map.put(B,2);
map.put(C,3); (String key:map.keySet()){
System.out.println(key ++ map.get(key));
(Map.Entry< String,Integer> entry:map.entrySet()){
String key = entry.getKey()。toString();
整数值= entry.getValue();
System.out.println(key,+ key +value+ value);
}
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.
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);
}
这篇关于在Java ConcurrentHashMap中打印所有键/值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!