在Java ConcurrentHashMap中打印所有键/值对

我试图简单地在ConcurrentHashMap中打印所有键/值对。

我在网上找到了这个代码,我认为会这样做,但它似乎是获取有关桶/哈希码的信息。 其实说实话输出很奇怪,可能我的程序不正确,但我首先要确保这部分是我想要使用的。

for (Entry entry : wordCountMap.entrySet()) { String key = entry.getKey().toString(); Integer value = entry.getValue(); System.out.println("key, " + key + " value " + value); } 

这为大约10个不同的键提供输出,其计数似乎是映射到插入的总插入数的总和。

我测试了你的代码并正常工作。 我添加了一个小型演示,用另一种方法打印地图中的所有数据:

 ConcurrentHashMap map = new ConcurrentHashMap(); 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 entry : map.entrySet()) { String key = entry.getKey().toString(); Integer value = entry.getValue(); System.out.println("key, " + key + " value " + value); } 

HashMap将forEach作为其结构的一部分。 您可以将其与lambda表达式一起使用,以打印出一行内容,例如:

 map.forEach((k,v)-> System.out.println(k+", "+v)); 

你可以做点什么

 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。

  //best and simple way to show keys and values //initialize map Map map = new HashMap(); //Add some values map.put(1, "Hi"); map.put(2, "Hello"); // iterate map using entryset in for loop for(Entry entry : map.entrySet()) { //print keys and values System.out.println(entry.getKey() + " : " +entry.getValue()); } //Result : 1 : Hi 2 : Hello 

ConcurrentHashMapHashMap类非常相似,只是ConcurrentHashMap提供了内部维护的并发性。 这意味着在multithreading应用程序中访问ConcurrentHashMap时不需要具有同步块。

要获得ConcurrentHashMap所有键值对,下面与您的代码类似的代码可以完美地工作:

 //Initialize ConcurrentHashMap instance ConcurrentHashMap m = new ConcurrentHashMap(); //Print all values stored in ConcurrentHashMap instance for each (Entry e : m.entrySet()) { System.out.println(e.getKey()+"="+e.getValue()); } 

上面的代码在您的应用程序的multithreading环境中相当有效。 我说“合理有效”的原因是,上面的代码还提供了线程安全性,但仍然会降低应用程序的性能。

希望这对你有所帮助。

工作100%肯定尝试此代码获取所有hashmap键和值

 static HashMap 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); } }