Java HashMap.clear() – Examples

In this tutorial, we will learn about the Java HashMap.clear() function, and learn how to use this function to clear all the mappings in this HashMap, with the help of examples.

clear()

HashMap.clear() is used to remove all of the mappings from this HashMap.

Syntax

The syntax of clear() function is

clear()

Returns

This function returns void.

Example 1 – clear()

In this example, we will create a HashMap<Integer, String> hashMap and put some key-value pairs into it. Now, we shall clear this HashMap using HashMap.clear() method. We will print the HashMap before and after clearing the items.

Java Program

import java.util.HashMap;

public class Example{ 
	public static void main(String[] args) {
		HashMap<Integer,String> hashMap=new HashMap<>(); 
		hashMap.put(1,"A");
		hashMap.put(2,"B");
		hashMap.put(3,"C");
		hashMap.put(4,"D");
		System.out.println("HashMap before clear : "+hashMap);
		
		hashMap.clear();
		System.out.println("HashMap after  clear : "+hashMap);
	}
}

Output

HashMap before clear : {1=A, 2=B, 3=C, 4=D}
HashMap after  clear : {}

Example 2 – clear()

In this example, we will initialize a HashMap<String, String> hashMap. We will use clear() method on this HashMap and clear the items in this HashMap.

Java Program

import java.util.HashMap;

public class Example{ 
	public static void main(String[] args) {
		HashMap<String,String> hashMap=new HashMap<>(); 
		hashMap.put("a","Aaa");
		hashMap.put("b","Bbb");
		hashMap.put("c","Ccc");
		hashMap.put("d","Ddd");
		System.out.println("HashMap before clear : "+hashMap);
		
		hashMap.clear();
		System.out.println("HashMap after  clear : "+hashMap);
	}
}

Output

HashMap before clear : {a=Aaa, b=Bbb, c=Ccc, d=Ddd}
HashMap after  clear : {}

Example 2 – clear() – HashMap = null

In this example, we will initialize a HashMap<String, String> hashMap with null. We will call clear() method on this HashMap. Since this HashMap is null, clear() should throw java.lang.NullPointerException.

Java Program

import java.util.HashMap;

public class Example{ 
	public static void main(String[] args) {
		HashMap<String,String> hashMap = null; 
		System.out.println("HashMap before clear : "+hashMap);
		
		hashMap.clear();
		System.out.println("HashMap after  clear : "+hashMap);
	}
}

Output

HashMap before clear : null
Exception in thread "main" java.lang.NullPointerException
	at Example.main(Example.java:8)

Conclusion

In this Java Tutorial, we have learnt the syntax of Java HashMap.clear() function, and also learnt how to use this function with the help of examples.