How to Clear All Key-value Pairs in a HashMap in Java


In this example we will show a common method to remove all values from HashMap object or clear HashMap. This is a simple example of using the clear() method to clear the key-value pairs in a HashMap.

Source Code

package com.beginner.examples;

import java.util.HashMap;

public class RemoveAllKey_Value {

	public static void main(String[] args) {

		// Create a HashMap Object
		HashMap map = new HashMap();

		// Add Key-Value
		map.put("1", "Jan");
		map.put("2", "Feb");
		map.put("3", "Mar");

		// Remove all key-value
		map.clear();
		
		//All clear
		System.out.println(map.get("1") + "n" + map.get("2") + "n"
				+ map.get("3"));

	}

}

Output:

null
null
null

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments