Tuesday, February 18, 2020

10 Examples of ConcurrentHashMap in Java

Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Prep, Oracle Java Exam Prep

Hello Java programmers, you might have heard about the ConcurrentHashMap class of java.util.concurrent package. If you don't let me tell you that ConcurrentHashMap is an important class in Java and you will often find yourself dealing with this class in a multithreaded and concurrent Java application. If you are wondering where to start and how to master this essential Java class then you have come to the right place. In this article, I have shared some of the frequently used examples of ConcurrentHashMap in Java-like how to create a ConcurrentHashMap, how to update a key or value, how to delete a key-value pair, how to check if a key exists in ConcurrentHashMap or not, how to add new key-value pairs, and how to retrieve values from ConcurrentHashMap in Java.

Once you have gone through these examples, you will have a better understanding of ConcurrentHashMap and you will be more confident on using them in your Java program without causing subtle bugs that are hard to find and fix.

10 Examples of ConcurrentHashMap in Java


Without wasting any more of your time, here are 10 useful examples of ConcurrentHashMap in Java.

1. How to create a ConcurrentHashMap with default capacity?

        ConcurrentHashMap programmingLanguages = new ConcurrentHashMap();
        System.out.println("Empty ConcurrentHashMap : " + programmingLanguages);

2. How to add objects into ConcurrentHashMap?

        programmingLanguages.put("Java", Integer.valueOf(18));
        programmingLanguages.put("Scala", Integer.valueOf(10));
        programmingLanguages.put("C++", Integer.valueOf(31));
        programmingLanguages.put("C", Integer.valueOf(41));
        System.out.println("ConcurrentHashMap with four mappings : " + programmingLanguages);

3. How to check if a key exists in ConcurrentHashMap or not?

        boolean isJavaExist = programmingLanguages.containsKey("Java");
        boolean isPythonExist = programmingLanguages.containsKey("Python");
        System.out.printf("Does Programming language Map has %s? %b %n", "Java", isJavaExist);
        System.out.printf("Does Programming language Map contains %s? %b %n", "Python", isPythonExist);

4. How to retrieve values from ConcurrentHashMap in Java?

        int howOldIsJava = programmingLanguages.get("Java");
        int howOldIsC = programmingLanguages.get("C");
        System.out.printf("How old is Java programming langugae? %d years %n", howOldIsJava);
        System.out.printf("How old is C langugae? %d years %n", howOldIsC);

5. How to check if a value exists in ConcurrentHashMap?

        boolean is41Present = programmingLanguages.containsValue(Integer.valueOf(41));
        boolean is31Present = programmingLanguages.containsValue(Integer.valueOf(31));
        System.out.printf("Does value 41 is present in ConcurrentHashMap? %b %n", is41Present);
        System.out.printf("Does value 31 is present in ConcurrentHashMap? %b %n", is31Present);

6. How to find Size of ConcurrentHashMap in Java?

        int numberOfMappings = programmingLanguages.size();
        System.out.printf("ConcurrentHashMap %s, contains %d mappings %n",
                programmingLanguages, numberOfMappings);

7. How to loop over ConcurrentHashMap in Java?

There are multiple ways to loop over a ConcurrentHashMap in Java. In fact, you can use all the four ways to iterate over the Map with ConcurrentHashMap as well. Ultimately, it also implements the java.utill.Map interface hence it obeys the contract of Map

        Set> entrySet = programmingLanguages.entrySet();
        for (Map.Entry mapping : entrySet) {
            System.out.printf("Key : %s, Value: %s %n", mapping.getKey(), mapping.getValue());
        }

8. PutIfAbsent Example - Adding keys only if it's not present in ConcurrentHashMap?

        System.out.printf("Before : %s %n", programmingLanguages);
        programmingLanguages.putIfAbsent("Java", 22); // Already exists
        System.out.printf("After : %s %n", programmingLanguages);

        programmingLanguages.put("Python", 23);  // Added
        System.out.printf("After : %s %n", programmingLanguages);

9. How to replace a Mapping in ConcurrentHashMap?

You can use the replace method to update the value of a key in ConcurrentHashMap. This method takes both key and value and updates the old value with the new one as shown below:

        programmingLanguages.replace("Java", 20);
        System.out.println("ConcurrentHashMap After replace : " + programmingLanguages);

10. How to remove key values from ConcurrentHashMap in Java?

You can use the remove() method of ConcurrentHashMap to remove the mapping from the Map. This method will remove both key and values and size of ConcurrentHashMap will decrease by one as shown in the following example:

        programmingLanguages.remove("C++");
        System.out.println("ConcurrentHashMap After remove : " + programmingLanguages);

11. How to remove keys, while Iterating over ConcurrentHashMap?

        Iterator keys = programmingLanguages.keySet().iterator();
        while (keys.hasNext()) {
            System.out.printf("Removing key %s from ConcurrentHashMap %n", keys.next());
            keys.remove();
        }

12. How to check if ConcurrentHashMap is empty in Java?

You can use the isEmpty() method of ConcurrentHashMap to check if the given Map is empty or not. This method will return true if ConcurrentHashMap doesn't have any mapping as shown in following example:

boolean isEmpty = programmingLanguages.isEmpty();
System.out.printf("Is ConcurrentHashMap %s is empty? %b ", programmingLanguages, isEmpty);

Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Prep, Oracle Java Exam Prep

ConcurrentHashMap Examples Java


Here is the complete Java Program which you can copy paste in Eclpse or run it from command line to play with:

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

/**
  * Java program to demonstrate how to use Concurrent HashMap in Java by simple examples.
  *
  * @author javin
  */

public class ConcurrentHashMapExamples{

    public static void main(String args[]) {

        // Creates a ConcurrentHashMap with default capacity
        ConcurrentHashMap programmingLanguages = new ConcurrentHashMap();
        System.out.println("Empty ConcurrentHashMap : " + programmingLanguages);


        // Adding objects into ConcurrentHashMap
        programmingLanguages.put("Java", Integer.valueOf(18));
        programmingLanguages.put("Scala", Integer.valueOf(10));
        programmingLanguages.put("C++", Integer.valueOf(31));
        programmingLanguages.put("C", Integer.valueOf(41));
        System.out.println("ConcurrentHashMap with four mappings : " + programmingLanguages);


        // Checking if a key exists in ConcurrentHashMap or not
        boolean isJavaExist = programmingLanguages.containsKey("Java");
        boolean isPythonExist = programmingLanguages.containsKey("Python");
        System.out.printf("Does Programming language Map has %s? %b %n", "Java", isJavaExist);
        System.out.printf("Does Programming language Map contains %s? %b %n", "Python", isPythonExist);


        // Retrieving values from ConcurrentHashMap in Java
        int howOldIsJava = programmingLanguages.get("Java");
        int howOldIsC = programmingLanguages.get("C");
        System.out.printf("How old is Java programming langugae? %d years %n", howOldIsJava);
        System.out.printf("How old is C langugae? %d years %n", howOldIsC);


        // Checking if a value exists in ConcurrentHashMap
        boolean is41Present = programmingLanguages.containsValue(Integer.valueOf(41));
        boolean is31Present = programmingLanguages.containsValue(Integer.valueOf(31));
        System.out.printf("Does value 41 is present in ConcurrentHashMap? %b %n", is41Present);
        System.out.printf("Does value 31 is present in ConcurrentHashMap? %b %n", is31Present);


        // Finding Size of ConcurrentHashMap
        int numberOfMappings = programmingLanguages.size();
        System.out.printf("ConcurrentHashMap %s, contains %d mappings %n",
                programmingLanguages, numberOfMappings);


        // Loop over ConcurrentHashMap in Java
        Set> entrySet = programmingLanguages.entrySet();
        for (Map.Entry mapping : entrySet) {
            System.out.printf("Key : %s, Value: %s %n", mapping.getKey(), mapping.getValue());
        }


        //PutIfAbsent Example - Adding keys only if its not present in ConcurrentHashMap
        System.out.printf("Before : %s %n", programmingLanguages);

        programmingLanguages.putIfAbsent("Java", 22); // Already exists
        System.out.printf("After : %s %n", programmingLanguages);

        programmingLanguages.put("Python", 23);  // Added
        System.out.printf("After : %s %n", programmingLanguages);


        // Replacing a Mapping in ConcurrentHashMap
        programmingLanguages.replace("Java", 20);
        System.out.println("ConcurrentHashMap After replace : " + programmingLanguages);


        // Removing key values from ConcurrentHashMap
        programmingLanguages.remove("C++");
        System.out.println("ConcurrentHashMap After remove : " + programmingLanguages);


        // Removing Keys, while Iterating over ConcurrentHashMap
        Iterator keys = programmingLanguages.keySet().iterator();
        while (keys.hasNext()) {
            System.out.printf("Removing key %s from ConcurrentHashMap %n", keys.next());
            keys.remove();

        }


        // How to check if ConcurrentHashMap is empty
        boolean isEmpty = programmingLanguages.isEmpty();
        System.out.printf("Is ConcurrentHashMap %s is empty? %b ", programmingLanguages, isEmpty);

    }

}

Output:

Empty ConcurrentHashMap : {}
ConcurrentHashMap with four mappings : {C=41, Scala=10, Java=18, C++=31}
Does Programming language Map has Java? true
Does Programming language Map contains Python? false
How old is Java programming langugae? 18 years
How old is C langugae? 41 years
Does value 41 is present in ConcurrentHashMap? true
Does value 31 is present in ConcurrentHashMap? true
ConcurrentHashMap {C=41, Scala=10, Java=18, C++=31}, contains 4 mappings
Key : C, Value: 41
Key : Scala, Value: 10
Key : Java, Value: 18
Key : C++, Value: 31
Before : {C=41, Scala=10, Java=18, C++=31}
After : {C=41, Scala=10, Java=18, C++=31}
After : {C=41, Python=23, Scala=10, Java=18, C++=31}
ConcurrentHashMap After replace : {C=41, Python=23, Scala=10, Java=20, C++=31}
ConcurrentHashMap After remove : {C=41, Python=23, Scala=10, Java=20}
Removing key C from ConcurrentHashMap
Removing key Python from ConcurrentHashMap
Removing key Scala from ConcurrentHashMap
Removing key Java from ConcurrentHashMap
Is ConcurrentHashMap {} is empty? true

That's all about ConcurrentHashMap examples in Java. As I said, after going through these examples, you will have a better understanding of How ConcurrentHashMap works and how to use it properly. Now you have a good idea of how to create, add, update, search, and delete entries on a ConcurrentHashMap in Java.

Related Posts

0 comments:

Post a Comment