Friday, July 23, 2021

How to Iterate through ConcurrentHashMap and print all keys and values in Java? Example

Suppose you have a ConcurrentHashMap of String and Integer and you want to print all keys and values, how do you do that? This is a common, day-to-day programming task for Java programmers and there are many ways to do it. The Map interface provides several view methods e.g. keySet(), values(), and entrySet() to retrieve all keys, values, and all key and value pairs as entries. You can use respective methods to print all keys, all values, or all key values pairs. For printing, you also have multiple choices like you can either use enhanced for loop or Iterator, though later also provide you the facility to remove key-value pairs while printing if needed.

Though you should remember that these views are backed by Map, so when you remove a key-value pair from the entry set it will also be removed by the ConcurrentHashMap.

This technique is also the standard way to iterate over Map and print all key-value pairs. You can use this technique to print all keys, values, or entries with any Map implementations including HashMap, Hashtable, LinkedHashMap, EnumMap, IdentityHashMap, WeakHashMap, or any other future implementations. How is that possible? because we are using the methods defined on Map interface and not on ConcurrentHashMap.

It's guaranteed that the new Map implementation will implement the java.util.Map interface hence it will have the keySet(), values(), and entrySet() method, which means this code will work there.

This is also the beauty of programming for interfaces than implementations, one of the important object-oriented design principles. and you should always do that in Java or any other object-oriented programming language. To read more about it I strongly suggest reading the first few chapters of Head First object-oriented Analysis and design book.





Print all keys and values of ConcurrentHashMap

Here is our sample Java program to print all entries from ConcurrentHashMap. I have initially created a Map with String as keys and Integer as values. It actually contains the price of popular tablets and Kindle devices. Later I had shown how to print all keys using keySet() and all key and value pairs using entrySet() in combination with for loop and Iterator.

Btw, if you are not familiar with concurrent collections e.g. ConcurrentHashMap, and want to learn how they are different from traditional HashMap then I suggest you refer to Core Java Volume 1 - Fundamentals by Cay S. Horstmann, one of the great books to learn the basics of Java.

How to print all keys and values of ConcurrentHashMap in Java



Java Program to iterate and print keys and values of ConcurrentHashMap

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/*
 * Java Program to print all key-value pairs of ConcurrentHashMap 
 * There are multiple ways to do this e.g. by using keySet(), entrySet()
 * in combination of for loop and iterator.
 */

public class ConcurrentHashMapDemo {

  public static void main(String[] args) {

    Map<String, Integer> map = new ConcurrentHashMap<String, Integer>();
    map.put("Kindle", 99);
    map.put("Samsung tablet", 200);
    map.put("iPad", 1000);
    map.put("iPad Mini", 600);

    // printing all keys of ConcurrentHashMap
    System.out.println("All keys of ConcurrentHashMap");
    for (String key : map.keySet()) {
      System.out.println(key + " : " + map.get(key));
    }

    // printing all keys and values pairs of ConcurrentHashMap
    System.out.println("Printing all keys and values of ConcurrentHashMap");
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
      String key = entry.getKey().toString();
      Integer value = entry.getValue();
      System.out.println("key: " + key + " value: " + value);
    }

    // you can also use Iterator with EntrySet as shown below
    Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
    Iterator<Map.Entry<String, Integer>> itr = entrySet.iterator();

    while (itr.hasNext()) {
      Map.Entry<String, Integer> entry = itr.next();
      String key = entry.getKey();
      Integer value = entry.getValue();
      System.out.println("key: " + key + " value: " + value);
    }

  }

}

Output
iPad Mini : 600
Kindle : 99
Samsung tablet : 200
iPad : 1000
key: iPad Mini value: 600
key: Kindle value: 99
key: Samsung tablet value: 200
key: iPad value: 1000
key: iPad Mini value: 600
key: Kindle value: 99
key: Samsung tablet value: 200
key: iPad value: 1000

You can see we have successfully printed all keys and all key-value pairs from ConcurrentHashMap by using keySet() and entrySet() in Java. I haven't tried removing a key-value pair, but you can do, but only while traversing a Map using Iterator.


Btw, if you are not familiar with ConcurrentHashMap and how it achieves better scalability than synchronized HashMap in Java then you should take a look at the below diagram. You can see that it divides the whole map into Segments and at a time only one of those Segments is locked instead of the entire Map, which is the case with synchronized HashMap. 

This helps it to achieve better Scalability. (see Big Java: Early Objects to learn more about the internal working of ConcurrentHashMap in Java)


How to iterate over ConcurentHashMap and print all keys and values in Java



That's all about how to print all key and value pairs from ConcurrentHashMap in Java. As I said, you can use this technique to print keys, values, and entries with any Map classes e.g. HashMap, LinkedHashMap, or TreeMap. You can also remove mapping using the remove() method of Iterator and it will delete entry not only from the entry set but also from the Map itself. As long as you are using methods from the Map interface, it's guaranteed that code will work with any Map implementations in the future.

Related Java ConcurrentHashMap articles you may like
  • Difference between HashMap, ConcurrentHashMap, and Hashtable in Java? (answer)
  • Difference between Synchronized and Concurrent Collection in Java? (answer)
  • 5 Concurrent Collections Every Java Developer Should Know (list)
  • Difference between a fail-fast and fail-safe Iterator in Java? (answer)
  • Difference between ConcurrentHashMap and HashMap in Java? (answer)
  • Frequently asked Java Collection Interview Questions and Answers (list)

No comments:

Post a Comment