The isEmpty()
method of ConcurrentHashMap
is used to check if the specified ConcurrentHashMap
object is empty.
A
ConcurrentHashMap
is a thread-safe version of a HashMap that allows concurrent read and thread-safe update operations. Internally, it uses a Hashtable. TheConcurrentHashMap
object is divided into multiple portions according to the concurrency level. During an update operation, only a specific portion of the map is locked instead of the whole map being locked. Read more here.
public boolean isEmpty()
This method doesn’t take any argument(s).
This method returns True
if the map doesn’t have any mappings. Otherwise, it returns False
.
The following example demonstrates how to use the isEmpty()
method.
import java.util.concurrent.ConcurrentHashMap;class ConcurrentHashMapisEmptyExample {public static void main( String args[] ) {ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>();System.out.println("\nChecking if ConcurrentHashMap is empty : "+ map.isEmpty());map.put(1, "one");map.put(2, "two");System.out.println("\nAfter Adding some mappings to the map");System.out.println("\nChecking if ConcurrentHashMap is empty : "+ map.isEmpty());}}
In the code written above:
In line 1, we import the ConcurrentHashMap
class.
In line 4, we create a ConcurrentHashMap
object with the name map
.
In line 5, we use the isEmpty()
method to check if the map
is empty. We get True
as a result because the map
object is empty.
In lines 6 and 7, we use the put()
method to add two mappings ({1=one, 2=two}
) to the map
object.
In line 9, we use the isEmpty()
method to check if the map
is empty. We get False
as a result because the map
object is not empty.