简体   繁体   English

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

[英]Print all key/value pairs in a Java ConcurrentHashMap

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 个不同键的输出,计数似乎是映射到总插入次数的总和。

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. HashMap 将forEach作为其结构的一部分。 You can use that with a lambda expression to print out the contents in a one liner such as:您可以将其与 lambda 表达式一起使用以打印出一行中的内容,例如:

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

or

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

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。

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

The ConcurrentHashMap is very similar to the HashMap class, except that ConcurrentHashMap offers internally maintained concurrency. ConcurrentHashMapHashMap类非常相似,除了ConcurrentHashMap提供内部维护的并发性。 It means you do not need to have synchronized blocks when accessing ConcurrentHashMap in multithreaded application.这意味着在多线程应用程序中访问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.希望这对你有帮助。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM