DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Tired of Spring Overhead? Try Dropwizard for Your Next Java Microservice
  • Using Python Libraries in Java
  • Designing a Java Connector for Software Integrations
  • How to Convert XLS to XLSX in Java

Trending

  • Designing a Java Connector for Software Integrations
  • Is Agile Right for Every Project? When To Use It and When To Avoid It
  • Developers Beware: Slopsquatting and Vibe Coding Can Increase Risk of AI-Powered Attacks
  • Memory Leak Due to Time-Taking finalize() Method
  1. DZone
  2. Coding
  3. Java
  4. 10 Examples of ConcurrentHashMap in Java

10 Examples of ConcurrentHashMap in Java

Below are some of the frequent operations around Java's ConcurrentHashMap, like how to create a ConcurrentHashMap, how to update a key or value.

By 
Javin Paul user avatar
Javin Paul
·
Updated Oct. 22, 20 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
17.5K Views

Join the DZone community and get the full member experience.

Join For Free
As a Java programmer, you might have heard about the ConcurrentHashMapclass 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 in 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. By these examples, you will learn how to work with ConcurrentHashMap in Java, like creating a map, inserting key-value pairs, updating a key-value pair, deleting a mapping, check if a key or value exists in the map, iterating over keys or values, and so on.

1. How to Create a ConcurrentHashMap With Default Capacity

The first thing first, let's learn how to create a concurrent hashmap in Java. Here is an example of creating an empty ConcurrentHashMapw ith default capacity.

Java
 




xxxxxxxxxx
1


 
1
ConcurrentHashMap programmingLanguages = new ConcurrentHashMap();
2

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


2. How to Add Objects Into ConcurrentHashMap

Once you have created a ConcurrentHashMap, it's time to add some mapping. let's store some keys and values into a ConcurrentHashMap in Java. If you look at the below code its no different than the HashMa examples of adding mapping which we have seen before, the only difference is that its thread-safe.

Java
 




xxxxxxxxxx
1


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


3. How to Check if a Key Exists in ConcurrentHashMap or not

Now that you have added mapping, its time to check is key exists in the ConcurrentHashMap or not. This time we will use the containsKey() method from the Map interface which is also available on CHM because CHM implements the Map interface.

Java
 




xxxxxxxxxx
1


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


4. How to Retrieve Values From ConcurrentHashMap in Java

Here is an example of retrieving values from ConcurrentHashMap in Java. This example is very similar to any other map like HashMap or HashTable, as we are using the same get() method to retrieve values from ConcurrentHashMap in Java.

Java
 




xxxxxxxxxx
1


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


5. How to Check if a Value Exists in ConcurrentHashMap

Here is an example of checking if a value exists in ConcurrentHashMap or not. Again, this example is very similar to the HashMap containsValue() example we have seen before.

Java
 




xxxxxxxxxx
1


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



List hierarchy in Java


6. How to Find Size of ConcurrentHashMap in Java

You can use the size() method to find out how many key-value pairs are present in the ConcurrentHashMap. The size() method returns the total number of mappings.

Java
 




xxxxxxxxxx
1


 
1
int numberOfMappings = programmingLanguages.size();
2
System.out.printf("ConcurrentHashMap %s, contains %d mappings %n",
3
                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

Java
 




xxxxxxxxxx
1


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


8. PutIfAbsent Example - Adding Keys Only if It's Not Present in ConcurrentHashMap?

This is a useful method which can be used to only insert element if it's not already present in the map or dictionary. This is also a common ConcurrentHashMap interview question which is often asked to beginners. 

Java
 




xxxxxxxxxx
1


 
1
System.out.printf("Before : %s %n", programmingLanguages);
2
programmingLanguages.putIfAbsent("Java", 22); 
3
System.out.printf("After : %s %n", programmingLanguages);
4

           
5
programmingLanguages.put("Python", 23);  
6
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:

Java
 




xxxxxxxxxx
1


 
1
programmingLanguages.replace("Java", 20);
2
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 the size of ConcurrentHashMap will decrease by one as shown in the following example:

Java
 




xxxxxxxxxx
1


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



After running this code the mapping for the "C++" key will be removed.

11. How to Remove Keys, While Iterating Over ConcurrentHashMap

Here is the code example of removing keys while iterating over ConcurrentHashMap in Java. Again, it's no different than removing keys from HashMap as we are using the same remove() method from the Map interface which is also inherited by ConcurrentHashMap class in Java.

Java
 




xxxxxxxxxx
1


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



The remove() method removes the current Key from the ConcurrentHashMap, just like Iterator does for List, Set, and Map.

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 the following example:

Java
 




xxxxxxxxxx
1


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



ConcurrentHashMap Examples Java

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

Java
 




xxxxxxxxxx
1
91


 
1
import java.util.Iterator; 
2
import java.util.Map; 
3
import java.util.Set; 
4
import java.util.concurrent.ConcurrentHashMap;   
5

           
6
/** * Java program to demonstrate how to use Concurrent HashMap in Java by simple examples. * * @author javin */   
7
public class ConcurrentHashMapExamples{   
8
  public static void main(String args[]) {   
9
    // Creates a ConcurrentHashMap with default capacity 
10
    ConcurrentHashMap programmingLanguages = new ConcurrentHashMap();
11
    System.out.println("Empty ConcurrentHashMap : " + programmingLanguages);       // Adding objects into ConcurrentHashMap 
12
    programmingLanguages.put("Java", Integer.valueOf(18));
13
    programmingLanguages.put("Scala", Integer.valueOf(10));
14
    programmingLanguages.put("C++", Integer.valueOf(31));
15
    programmingLanguages.put("C", Integer.valueOf(41));
16
    
17
    System.out.println("ConcurrentHashMap with four mappings : " +
18
                       programmingLanguages);       
19
    
20
    // Checking if a key exists in ConcurrentHashMap or not 
21
    boolean isJavaExist = programmingLanguages.containsKey("Java"); 
22
    boolean isPythonExist = programmingLanguages.containsKey("Python");
23
    System.out.printf("Does Programming language Map has %s? %b %n", "Java",
24
                      isJavaExist); 
25
    System.out.printf("Does Programming language Map contains %s? %b %n",
26
                      "Python", isPythonExist);       
27
    
28
    // Retrieving values from ConcurrentHashMap in Java 
29
    int howOldIsJava = programmingLanguages.get("Java"); 
30
    int howOldIsC = programmingLanguages.get("C"); 
31
    
32
    System.out.printf("How old is Java programming langugae? %d years %n",
33
                      howOldIsJava); 
34
    System.out.printf("How old is C langugae? %d years %n", howOldIsC);       
35
    
36
    // Checking if a value exists in ConcurrentHashMap 
37
    boolean is41Present = programmingLanguages.containsValue(
38
      Integer.valueOf(41)); 
39
    boolean is31Present = programmingLanguages.containsValue(
40
      Integer.valueOf(31)); 
41
    
42
    System.out.printf("Does value 41 is present in ConcurrentHashMap? %b %n",
43
                      is41Present); 
44
    System.out.printf("Does value 31 is present in ConcurrentHashMap? %b %n",
45
                      is31Present);       
46
    
47
    // Finding Size of ConcurrentHashMap 
48
    int numberOfMappings = programmingLanguages.size();
49
    System.out.printf("ConcurrentHashMap %s, contains %d mappings %n",
50
                      programmingLanguages, numberOfMappings);       
51
    
52
    // Loop over ConcurrentHashMap in Java 
53
    Set> entrySet = programmingLanguages.entrySet(); 
54
    for (Map.Entry mapping : entrySet) { 
55
      System.out.printf("Key : %s, Value: %s %n", mapping.getKey(),
56
                        mapping.getValue()); 
57
    }       
58
    
59
    //PutIfAbsent Example - Adding keys only if its not present in 
60
    //ConcurrentHashMap
61
    System.out.printf("Before : %s %n", programmingLanguages);  
62
    programmingLanguages.putIfAbsent("Java", 22); // Already exists
63
    
64
    System.out.printf("After : %s %n", programmingLanguages);  
65
    programmingLanguages.put("Python", 23); // Added 
66
    
67
    System.out.printf("After : %s %n", programmingLanguages);       
68
    // Replacing a Mapping in ConcurrentHashMap
69
    programmingLanguages.replace("Java", 20);
70
    System.out.println("ConcurrentHashMap After replace : " +
71
                       programmingLanguages);       
72
    
73
    // Removing key values from ConcurrentHashMap
74
    programmingLanguages.remove("C++"); 
75
    System.out.println("ConcurrentHashMap After remove : " +
76
                       programmingLanguages);       
77
    
78
    // Removing Keys, while Iterating over ConcurrentHashMap 
79
    Iterator keys = programmingLanguages.keySet().iterator(); 
80
    while (keys.hasNext()) { 
81
      System.out.printf("Removing key %s from ConcurrentHashMap %n",
82
                        keys.next()); 
83
      keys.remove();   
84
    }       
85
    
86
    // How to check if ConcurrentHashMap is empty 
87
    boolean isEmpty = programmingLanguages.isEmpty(); 
88
    System.out.printf("Is ConcurrentHashMap %s is empty? %b ",
89
                      programmingLanguages, isEmpty);   
90
  }       
91
}



Output:

Plain Text
 




xxxxxxxxxx
1
23


 
1
Empty ConcurrentHashMap : {}
2
ConcurrentHashMap with four mappings : {C=41, Scala=10, Java=18, C++=31}
3
Does Programming language Map has Java? true
4
Does the Programming language Map contain Python? false
5
How old is Java programming language? 18 years
6
How old is C language? 41 years
7
Does value 41 is present in ConcurrentHashMap? true
8
Does value 31 is present in ConcurrentHashMap? true
9
ConcurrentHashMap {C=41, Scala=10, Java=18, C++=31}, contains 4 mappings
10
Key: C, Value: 41
11
Key: Scala, Value: 10
12
Key: Java, Value: 18
13
Key : C++, Value: 31
14
Before : {C=41, Scala=10, Java=18, C++=31}
15
After : {C=41, Scala=10, Java=18, C++=31}
16
After : {C=41, Python=23, Scala=10, Java=18, C++=31}
17
ConcurrentHashMap After replace : {C=41, Python=23, Scala=10, Java=20, C++=31}
18
ConcurrentHashMap After remove : {C=41, Python=23, Scala=10, Java=20}
19
Removing key C from ConcurrentHashMap
20
Removing key Python from ConcurrentHashMap
21
Removing key Scala from ConcurrentHashMap
22
Removing key Java from ConcurrentHashMap
23
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.

Thanks for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

Java (programming language)

Published at DZone with permission of Javin Paul, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Tired of Spring Overhead? Try Dropwizard for Your Next Java Microservice
  • Using Python Libraries in Java
  • Designing a Java Connector for Software Integrations
  • How to Convert XLS to XLSX in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!