Sunday, June 4, 2023

12 Examples of ConcurrentHashMap in Java? put, get, containsKey, containsValue, kyeSet, replace, and remove Examples

Sure! Here are 12 examples demonstrating various operations with ConcurrentHashMap in Java, including put(), get(), containsKey(), containsValue(), keySet(), replace(), and remove(): 

1. Creating a ConcurrentHashMap:


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

public class ConcurrentHashMapExample {
    public static void main(String[] args) {
        // Creating a ConcurrentHashMap
        ConcurrentHashMap concurrentHashMap = new ConcurrentHashMap<>();
    }
}


2. Adding key-value pairs using put():


concurrentHashMap.put("Key1", 1);
concurrentHashMap.put("Key2", 2);
concurrentHashMap.put("Key3", 3);

3. Retrieving a value using get():


int value = concurrentHashMap.get("Key1");
System.out.println("Value: " + value);

4. Checking if a key exists using containsKey():


boolean containsKey = concurrentHashMap.containsKey("Key2");
System.out.println("Contains Key: " + containsKey);

5. Checking if a value exists using containsValue():


boolean containsValue = concurrentHashMap.containsValue(3);
System.out.println("Contains Value: " + containsValue);

6. Getting the set of keys using keySet():


Set keySet = concurrentHashMap.keySet();
System.out.println("Key Set: " + keySet);

7. Replacing a value for a given key using replace():


concurrentHashMap.replace("Key1", 10);

8. Removing a key-value pair using remove():


concurrentHashMap.remove("Key2");

9. Removing a key-value pair if the key-value pair exists using remove():


concurrentHashMap.remove("Key3", 3);

10. Removing a key-value pair only if the key-value pair matches the existing entry using remove():


concurrentHashMap.remove("Key1", 5);

11.Iterating over the key-value pairs using a for-each loop:


for (Map.Entry entry : concurrentHashMap.entrySet()) {
    String key = entry.getKey();
    int value = entry.getValue();
    System.out.println(key + ": " + value);
}

12. concurrentHashMap.clear();


concurrentHashMap.clear();

These examples demonstrate various operations you can perform on a ConcurrentHashMap in Java. Feel free to modify and combine them to suit your specific needs.

No comments:

Post a Comment