Java ConcurrentHashMap - clear()

The clear function is used to clear up the mapping between the key value pairs. This way, the ConcurrentHashMap mappings would be cleared.


public void clear()

Let us see an example −


 Live Demo

import java.util.concurrent.ConcurrentHashMap;
import java.util.*;
public class Demo{
   public static void main(String[] args){
      Map<String, String> my_map = new ConcurrentHashMap<String, String>();
      my_map.put("This", "35");
      my_map.put("is", "78");
      my_map.put("sample", "99");
      System.out.println("The map contains the below elements " + my_map);
      System.out.println("The elements after the clear function is called on it " + my_map);


The map contains the below elements {This=35, is=78, sample=99}
The elements after the clear function is called on it {}

A class named Demo contains the main function. Here, a new instance of the Map is created, and elements are added to it using the ‘put’ function. The elemnts are displayed and next, the map is cleared. Now, the map won’t contain anything and this can be seen when the map is displayed again.