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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22663107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:09:40  来源:igfitidea点击:

Print all key/value pairs in a Java ConcurrentHashMap

javacollectionshashmapconcurrenthashmap

提问by DanGordon

I am trying to simply print all key/value pair(s) in a ConcurrentHashMap.

我试图简单地打印 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.

这给出了大约 10 个不同键的输出,计数似乎是映射到总插入次数的总和。

采纳答案by Slimu

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

回答by Shishir Kumar

The ConcurrentHashMapis very similar to the HashMapclass, except that ConcurrentHashMapoffers internally maintained concurrency. It means you do not need to have synchronized blocks when accessing ConcurrentHashMapin multithreaded application.

ConcurrentHashMap是非常相似的HashMap类,但ConcurrentHashMap内部维护并发优惠。这意味着ConcurrentHashMap在多线程应用程序中访问时不需要同步块。

To get all key-value pairs in ConcurrentHashMap, below code which is similar to your code works perfectly:

要获取 中的所有键值对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());
}

Above code is reasonably valid in multi-threaded environment in your application. The reason, I am saying 'reasonably valid' is that, above code yet provides thread safety, still it can decrease the performance of application.

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

Hope this helps you.

希望这对你有帮助。

回答by nikoo28

You can do something like

你可以做类似的事情

Iterator iterator = map.keySet().iterator();

while (iterator.hasNext()) {
   String key = iterator.next().toString();
   Integer value = map.get(key);

   System.out.println(key + " " + value);
}

Here 'map' is your concurrent HashMap.

这里的“地图”是您的并发 HashMap。

回答by Arpit Patel

Work 100% sure try this code for the get all hashmap key and value

工作 100% 确定尝试使用此代码获取所有哈希映射键和值

static HashMap<String, String> map = new HashMap<>();

map.put("one"  " a " );
map.put("two"  " b " );
map.put("three"  " c " );
map.put("four"  " d " );

just call this method whenever you want to show the HashMap value

只要你想显示 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);
        }
    } 

回答by Khalid Habib

  //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

回答by Rick Il Grande

The HashMap has forEachas part of its structure. You can use that with a lambda expression to print out the contents in a one liner such as:

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

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

or

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