To create a ConcurrentHashMap
in Java, you can use the following code:
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();Source:www.lautturi.com
This code creates a new ConcurrentHashMap
called map
that maps keys of type String
to values of type Integer
. The ConcurrentHashMap
is a class that provides thread-safe access to a hash map, allowing multiple threads to read and write to the map simultaneously without causing data corruption or race conditions.
You can then use the put
method of the ConcurrentHashMap
to add key-value pairs to the map, like this:
map.put("key1", 10); map.put("key2", 20);
To retrieve the value associated with a key, you can use the get
method, like this:
int value = map.get("key1"); // value will be 10
You can also use the size
method to get the number of key-value pairs in the map, and the isEmpty
method to check if the map is empty.