Java HashMap Remove Example

The HashMap.remove() method allows you to remove the mapping for the specified key from this map if present. The remove() method takes a single argument, which is the key. The key is exactly that within the HashMap.

In our example code, we fill our HashMap with key/values where the key is the two digit state code and the value is the full state name. To remove California from our HashMap, we call remove() with “CA” and the key/value pair is removed.

Java HashMap Remove Source Code


import java.util.HashMap;

public class JavaHashMapRemove 

	public static void main(String[] args) 

		//Define an empty HashMap
		HashMap<String,String> jcdHashMap = new HashMap<String,String>();
		//Add random key/value pairs to the HashMap
		jcdHashMap.put("NC", "North Carolina");
		jcdHashMap.put("FL", "Florida");
		jcdHashMap.put("CA", "California");
		jcdHashMap.put("NY", "New York");
		jcdHashMap.put("SC", "South Carolina");
		jcdHashMap.put("GA", "Georgia");
		//Print out current key/values of HashMap
		System.out.println("jcdHashMap: "+jcdHashMap);
		System.out.println("Size: "+jcdHashMap.size());
		//Remove CA from our HashMap
		//Print out current key/values of HashMap after removing CA
		System.out.println("jcdHashMap: "+jcdHashMap);
		System.out.println("Size: "+jcdHashMap.size());



Java HashMap Remove Output

jcdHashMap: {SC=South Carolina, NC=North Carolina, FL=Florida, GA=Georgia, NY=New York, CA=California}
Size: 6

jcdHashMap: {SC=South Carolina, NC=North Carolina, FL=Florida, GA=Georgia, NY=New York}
Size: 5

Add a Comment

Your email address will not be published. Required fields are marked *