Certainly! The ConcurrentHashMap class in Java provides the getOrDefault() method, which allows you to retrieve the value associated with a given key in the map. If the key is present in the map, it returns the corresponding value; otherwise, it returns a default value that you provide.
Here's an example code snippet that demonstrates the usage of the getOrDefault() method:
import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentHashMapExample {
public static void main(String[] args) {
// Create a ConcurrentHashMap
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
// Add some key-value pairs to the map
map.put("apple", 5);
map.put("banana", 10);
map.put("orange", 8);
// Retrieve the value associated with a key using getOrDefault()
int value1 = map.getOrDefault("apple", 0);
System.out.println("Value of 'apple': " + value1); // Output: Value of 'apple': 5
int value2 = map.getOrDefault("grape", 0);
System.out.println("Value of 'grape': " + value2); // Output: Value of 'grape': 0
}
}
In the example above, we first create a ConcurrentHashMap called map. We then add some key-value pairs to the map using the put() method. The keys are strings ("apple", "banana", "orange"), and the values are integers.
Next, we use the getOrDefault() method to retrieve the values associated with two different keys: "apple" and "grape". The first call to getOrDefault() for the key "apple" returns the value 5 because it exists in the map. The second call for the key "grape" returns the default value 0 because it doesn't exist in the map.
The getOrDefault() method is useful when you want to retrieve a value from a ConcurrentHashMap but provide a default value in case the key is not present. This can help avoid NullPointerExceptions or handle missing keys more gracefully.