我试图简单地在ConcurrentHashMap中打印所有键/值对。
我在网上发现了这个代码,我认为会这样做,但似乎是获取有关存储桶/哈希码的信息。其实说实话输出很奇怪,可能我的程序不正确,但我首先要确保这部分是我想要使用的。
for (Entry<StringBuilder, Integer> entry : wordCountMap.entrySet()) {
String key = entry.getKey().toString();
Integer value = entry.getValue();
System.out.println("key, " + key + " value " + value);
}
这为大约10个不同的键提供输出,其计数似乎是到地图中的总插入数的总和。
答案 0 :(得分:29)
我测试了您的代码并正常运行。我添加了一个小型演示,用另一种方法打印地图中的所有数据:
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 :(得分:18)
HashMap将forEach
作为其结构的一部分。您可以将其与lambda表达式一起使用,以打印出一行内容,例如:
map.forEach((k,v)-> System.out.println(k+", "+v));
答案 2 :(得分:6)
您可以执行类似
的操作Iterator iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next().toString();
Integer value = map.get(key);
System.out.println(key + " " + value);
}
这里'map'是您的并发HashMap。
答案 3 :(得分: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
答案 4 :(得分:0)
ConcurrentHashMap
与HashMap
类非常相似,只是ConcurrentHashMap
提供了内部维护的并发性。这意味着在多线程应用程序中访问ConcurrentHashMap
时,您不需要具有同步块。
要获取ConcurrentHashMap
中的所有键值对,下面与代码类似的代码可以完美运行:
//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());
}
以上代码在您的应用程序的多线程环境中相当有效。我说“合理有效”的原因是,上面的代码还提供了线程安全性,但仍然会降低应用程序的性能。
希望这会对你有所帮助。
答案 5 :(得分:0)
工作100%肯定尝试使用此代码获取所有hashmap键和值
static HashMap<String, String> map = new HashMap<>();
map.put("one" " a " );
map.put("two" " b " );
map.put("three" " c " );
map.put("four" " d " );
只要您想显示HashMap值
,就调用此方法 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);
}
}