Home > Tutorial > Java HashMap Remove Example

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

package com.jcd.java.tutorials;

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());
		
		System.out.println();
		
		//Remove CA from our HashMap
		jcdHashMap.remove("CA");
		
		//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


Smedley
Posted by

Smedley

Smedley has been programming in Java for about twenty years. He enjoys sharing code samples to other fellow Java coders.

You may also like...

Leave a Reply

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

Copyright © 2018 JavaCodeDepot