This is how to remove all the key-value mappings from TreeMap and make it empty. We are using clear() method of TreeMap class to perform this update.
import java.util.TreeMap; public class RemoveAllExample { public static void main(String[] args) { // Create a TreeMap TreeMap<String, String> treemap = new TreeMap<String, String>(); // Add key-value pairs to the TreeMap treemap.put("Key1","Item1"); treemap.put("Key2","Item2"); treemap.put("Key3","Item3"); treemap.put("Key4","Item4"); treemap.put("Key5","Item5"); // TreeMap elements before calling clear() System.out.println("Before: TreeMap contains: "+treemap); // Make TreeMap empty /* public void clear(): It removes all of the mappings from * this map. The map will be empty after this call returns. */ treemap.clear(); //TreeMap elements after calling clear() System.out.println("After: TreeMap contains: "+treemap); } }
Output:
Before: TreeMap contains: {Key1=Item1, Key2=Item2, Key3=Item3, Key4=Item4, Key5=Item5} After: TreeMap contains: {}
Reference:
TreeMap – clear() method
Leave a Reply