Wednesday, May 15, 2024
HomeJava12 Examples of ConcurrentHashMap in Java? put, get, containsKey, containsValue, kyeSet, exchange,...

12 Examples of ConcurrentHashMap in Java? put, get, containsKey, containsValue, kyeSet, exchange, and take away Examples


Good day guys, in case you are new to Java programming and need to study ConcurrentHashMap class in Java then you may have come to the correct place. Earlier, I’ve shared the greatest books and greatest programs to study Java, and as we speak, I’m going to share 10 examples of utilizing ConcurrentHashMap in Java. As a Java programmer, you might need heard in regards to the ConcurrentHashMap class of java.util.concurrent bundle. For those who do not let me let you know that ConcurrentHashMap is a crucial class in Java and you’ll usually end up coping with this class in a multithreaded and concurrent Java software. If you’re questioning the place to start out and grasp this important Java class then you may have come to the correct place.

After getting gone by way of these examples, you should have a greater understanding of ConcurrentHashMap and you may be extra assured in utilizing them in your Java program with out inflicting refined bugs which are arduous to search out and repair.

Btw, in case you are new to the Java Programming world then I additionally counsel you undergo considered one of these greatest Java programming programs which cowl each OOP and Java. Additionally it is one of many inexpensive programs and newest. It covers new Java options launched in latest Java releases.

12 Examples of ConcurrentHashMap in Java

With out losing any extra of your time, listed here are 10 helpful examples of ConcurrentHashMap in Java. By these examples, you’ll discover ways to work with ConcurrentHashMap in Java, like making a map, inserting key-value pairs, updating a key-value pair, deleting a mapping, checking if a key or worth exists within the map, iterating over keys or values, and so forth.

1. Methods to create a ConcurrentHashMap with default capability?

The very first thing first, let’s discover ways to create a concurrent HashMap in Java. Right here is an instance of making an empty ConcurrentHashMapw ith default capability.

ConcurrentHashMap programmingLanguages = new ConcurrentHashMap();

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

     

2. Methods to add objects into ConcurrentHashMap?

After getting created a ConcurrentHashMap, it is time to add some mapping. let’s retailer some keys and values right into a ConcurrentHashMap in Java. For those who take a look at the under code it is no totally different than the HashMap examples of including mapping which we now have seen earlier than, the one distinction is that it is thread-safe.

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 4 mappings : " 
                             + programmingLanguages);

3. Methods to verify if a key exists in ConcurrentHashMap or not?

Now that you’ve added mapping, it is time to verify if the important thing exists within the ConcurrentHashMap or not. This time we’ll use the containsKey() methodology from the Map interface which can also be out there on CHM as a result of CHM implements the Map interface.

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 accommodates %s? %b %n",
                          "Python",  isPythonExist);

4. Methods to retrieve values from ConcurrentHashMap in Java?

Right here is an instance of retrieving values from ConcurrentHashMap in Java. This instance is similar to every other map like HashMap or Hashtable as we’re utilizing the identical get() methodology to retrieve values from ConcurrentHashMap in Java. 
int howOldIsJava = programmingLanguages.get("Java");
int howOldIsC = programmingLanguages.get("C");
System.out.printf("How previous is Java programming langugae? %d years %n",
                            howOldIsJava);
System.out.printf("How previous is C langugae? %d years %n", howOldIsC);

5. Methods to verify if a worth exists in ConcurrentHashMap?

Right here is an instance of checking if a worth exists in ConcurrentHashMap or not. Once more, this instance is similar to the HashMap containsValue() instance we now have seen earlier than. 

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

 If you wish to study extra about concurrent hashmap then you possibly can additional see a complete Java assortment course like these greatest Java Collections and Stream programs t to study extra about ConcurrentHashMap and different concurrent Assortment lessons. 

best course to learn ConcurrentHashMap in Java

6. Methods to discover the Dimension of ConcurrentHashMap in Java?

You should use the measurement() methodology to learn the way many key-value pairs are current within the ConcurrentHashMap.  The measurement() methodology returns the whole variety of mappings. 

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

7. Methods to loop over ConcurrentHashMap in Java?

There are a number of methods to loop over a ConcurrentHashMap in Java. In reality, you should use all 4 methods to iterate over the Map with ConcurrentHashMap as properly. Finally, it additionally implements the java.utill.Map interface therefore it obeys the contract of Map

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

8. PutIfAbsent Instance – Including keys provided that it isn’t current in ConcurrentHashMap?

It is a helpful methodology that can be utilized to solely insert components if it isn’t already current within the map or dictionary. 

System.out.printf("Earlier than : %s %n", programmingLanguages);
programmingLanguages.putIfAbsent("Java", 22); 
System.out.printf("After : %s %n", programmingLanguages);

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

9. Methods to exchange a Mapping in ConcurrentHashMap?

You should use the exchange() methodology to replace the worth of a key in ConcurrentHashMap. This methodology takes each key and worth and updates the previous worth with the brand new one as proven under:

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

10. Methods to take away key values from ConcurrentHashMap in Java?

You should use the take away() methodology of ConcurrentHashMap to take away the mapping from the Map. This methodology will take away each keys and values and the dimensions of ConcurrentHashMap will lower by one as proven within the following instance:

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

After operating this code the mapping for the “C++” key will likely be eliminated. 

11. Methods to take away keys, whereas Iterating over ConcurrentHashMap?

Right here is the code instance of eradicating keys whereas iterating over ConcurrentHashMap in Java. Once more, it is no totally different than eradicating keys from HashMap as we’re utilizing the identical take away() methodology from the Map interface which can also be inherited by ConcurrentHashMap class in Java. 

Iterator keys = programmingLanguages.keySet().iterator();
whereas (keys.hasNext()) {
    System.out.printf("Eradicating key %s from ConcurrentHashMap %n",
                         keys.subsequent());
    keys.take away();
}

The take away() methodology removes the present Key from the ConcurrentHashMap, similar to Iterator does for Listing, Set, and Map.  

12. Methods to verify if ConcurrentHashMap is empty in Java?

You should use the isEmpty() methodology of ConcurrentHashMap to verify if the given Map is empty or not. This methodology will return true if ConcurrentHashMap does not have any mapping as proven within the following instance:

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

These had been a few of the most typical examples of ConcurrentHashMap in Java. If you wish to study extra about this class or generally Java Concurrency and Collections, I counsel you be part of a complete course like The Full Java Masterclass on Udemy. It is also very up-to-date and up to date to incorporate new options from latest Java releases.

10 Examples of ConcurrentHashMap in Java

12 ConcurrentHashMap Examples Java – Tutorial

Right here is the entire Java Program which you’ll be able to copy-paste in Eclipse or run it from the 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 exhibit  use Concurrent HashMap in Java by easy examples.
  *
  * @creator javin
  */
 
public class ConcurrentHashMapExamples{
 
    public static void most important(String args[]) {
 
        // Creates a ConcurrentHashMap with default capability
        ConcurrentHashMap programmingLanguages = new ConcurrentHashMap();
        System.out.println("Empty ConcurrentHashMap : " 
                 + programmingLanguages);
 
 
        // Including 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 4 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 accommodates %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 previous is Java programming langugae?
                              %d years %n",
                                         howOldIsJava);
        System.out.printf("How previous is C langugae? %d years %n",
                                       howOldIsC);
 
 
 
        // Checking if a worth exists in ConcurrentHashMap
        boolean is41Present 
                    = programmingLanguages.containsValue(Integer.valueOf(41));
        boolean is31Present 
                    = programmingLanguages.containsValue(Integer.valueOf(31));
        System.out.printf("Does worth 41 is current in ConcurrentHashMap? %b %n",
                                     is41Present);
        System.out.printf("Does worth 31 is current in ConcurrentHashMap? %b %n",
                                     is31Present);
 

 
        // Discovering Dimension of ConcurrentHashMap
        int numberOfMappings = programmingLanguages.measurement();
        System.out.printf("ConcurrentHashMap %s, accommodates %d mappings %n",
                programmingLanguages, numberOfMappings);
 
 
 
        // Loop over ConcurrentHashMap in Java
        Set> entrySet = programmingLanguages.entrySet();
        for (Map.Entry mapping : entrySet) {
            System.out.printf("Key : %s, Worth: %s %n", mapping.getKey(),
                              mapping.getValue());
        }
 
 
        // PutIfAbsent Instance - Including keys solely
        // if its not current in ConcurrentHashMap
        System.out.printf("Earlier than : %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); 
 
 
        // Changing a Mapping in ConcurrentHashMap
        programmingLanguages.exchange("Java", 20);
        System.out.println("ConcurrentHashMap After exchange : " 
                    + programmingLanguages); 
 
 
        // Eradicating key values from ConcurrentHashMap
        programmingLanguages.take away("C++");
        System.out.println("ConcurrentHashMap After take away : " 
                  + programmingLanguages); 
 
 
        // Eradicating Keys, whereas Iterating over ConcurrentHashMap
        Iterator keys = programmingLanguages.keySet().iterator();
        whereas (keys.hasNext()) {
            System.out.printf("Eradicating key %s from ConcurrentHashMap %n",
            keys.subsequent());
            keys.take away();
 
        } 
 
 
        // Methods to verify if ConcurrentHashMap is empty
        boolean isEmpty = programmingLanguages.isEmpty();
        System.out.printf("Is ConcurrentHashMap %s is empty? %b ",
                   programmingLanguages, isEmpty);
 
    } 

 
}
 

Output:

Empty ConcurrentHashMap : {}
ConcurrentHashMap with 4 mappings : {C=41, Scala=10, Java=18, C++=31}
Does Programming language Map has Java? true
Does the Programming language Map include Python? false
How previous is Java programming language? 18 years
How previous is C language? 41 years
Does worth 41 is current in ConcurrentHashMap? true
Does worth 31 is current in ConcurrentHashMap? true
ConcurrentHashMap {C=41, Scala=10, Java=18, C++=31}, accommodates 4 mappings
Key: C, Worth: 41
Key: Scala, Worth: 10
Key: Java, Worth: 18
Key : C++, Worth: 31
Earlier than : {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 exchange : {C=41, Python=23, Scala=10, Java=20,
                                      C++=31}
ConcurrentHashMap After take away : {C=41, Python=23, Scala=10, Java=20}
Eradicating key C from ConcurrentHashMap
Eradicating key Python from ConcurrentHashMap
Eradicating key Scala from ConcurrentHashMap
Eradicating key Java from ConcurrentHashMap
Is ConcurrentHashMap {} is empty? true

That is all about ConcurrentHashMap examples in Java. As I mentioned, after going by way of these examples, you should have a greater understanding of how ConcurrentHashMap works and use it correctly. Now you may have a good suggestion of create, add, replace, search, and delete entries on a ConcurrentHashMap in Java. For those who suppose an important ConcurrentHashMap operation or instance is lacking, please be at liberty to counsel and I’ll add that for you. 

Different Java Articles you could like

Thanks for studying this Java ConcurrentHashMap tutorial thus far. For those who like this text then please share it with your folks and colleagues. You probably have any questions or suggestions then please drop a notice.

P. S. – If you’re an entire newbie to Java world and in search of a free Java course to start out your Java programming profession then you may also try Java Tutorial for Full Rookies (FREE) course on Udemy. It is fully free and also you simply want an Udemy account to hitch this course. 



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments