Java HashMap Sample Code

The Java HashMap class is one of my favorite collection classes. I use it all the time to store data. It reminds me a lot of the Vector class in C programming. If you need to store data in key/value pairs, the Java HashMap is a good option.

The sample Java source code below is a good example on how to create, add key/value pairs, get the HashMap size, search for a key, and output all of the key/value pairs. It’s basic but should provide a good understanding of HashMap basics.

Create Empty HashMap

Create a new HashMap instance using different key/value types based on what type of data you need to store. Depending on your programming need, you can pretty much use any data types as the key or value. While I would not use an Object (instance of a class) for the key, it can certainly be used for the value.

HashMap<String,String> stringStringHashMap = new HashMap<String,String>();

HashMap<String,Integer> stringIntegerHashMap = new HashMap<String,Integer>();

HashMap<Integer,String> integerStringHashMap = new HashMap<Integer,String>();

HashMap<String,Boolean> stringBooleanHashMap = new HashMap<String,Boolean>();

HashMap<String,Object> stringObjectHashMap = new HashMap<String,Object>();


Create HashMap Copy

You can create a new HashMap instance and fill it with all of the key/value mapping of another HashMap. After creating the parentHashMap, we add a key/value entry. We can then create childHashMap and load it with the contents of parentHashMap with one line.

HashMap<String,String> parentHashMap = new HashMap<String,String>();

parentHashMap.put("JavaCodeDepot", "javacodedepot.com");

HashMap<String,String> childHashMap = new HashMap<String,String>(parentHashMap);


Add Key/Value to HashMap

You can create a new HashMap instance with a String for the key and an Integer for the value and fill it with all of the key/value mapping of another HashMap.

HashMap<String,Integer> monthsHashMap = new HashMap<String,Integer>();

monthsHashMap.put("December", 12);


Check For Key/Value and Get Value From HashMap

It’s considered good programming to first check a HashMap for the existence of a key using the containsKey() method. If the HashMap contains the key, then use the get() method to pull the value. If it does not contain the key, well your done.

if(monthsHashMap.containsKey("December"))
{
	System.out.println("Decmeber is the "+monthsHashMap.get("December")+" month.");
}


Loop Through HashMap Entries

Once you have your HashMap filled with key/value pairs, you may want to print out the contents of the HashMap. A simple for loop will do the task nicely using the entrySet() method of HashMap Class.

for (Map.Entry<String,Integer> myMonth : monthsHashMap.entrySet()) 
{
	System.out.println("Key="+myMonth.getKey()+" Value="+myMonth.getValue());
}


There are a couple of things to keep in mind about the HashMap collection class.

  • If using an integer, you need to use Integer and not int.
  • HashMap does not maintain the order of the keys.
  • HashMap does allow null for both key and value.
  • HashMap is not thread safe (check out ConcurrentHashMap class).

Java HashMap Sample Source Code:

package com.jcd.java.tutorials;

import java.util.HashMap;
import java.util.Map;


public class JavaHashMap 
{

	public static void main(String[] args) 
	{

		//Create new HashMap that has key/value both set to String
		HashMap<String,String> stringHashMap = new HashMap<String,String>();
		
		//Add some values to our String HashMap
		stringHashMap.put("NC", "North Carolina");
		stringHashMap.put("SC", "South Carolina");
		stringHashMap.put("NY", "New York");
		stringHashMap.put("FL", "Florida");
	      
	    //Loop through HashMap to print out key/value pairs
		for (Map.Entry<String, String> myEntry : stringHashMap.entrySet()) 
		{
			System.out.println("Key="+myEntry.getKey()+" Value="+myEntry.getValue());
		}
		
		//Let's pull a value from HashMap using a specific key
		System.out.println("\nNC is short for "+stringHashMap.get("NC"));
		
		//See how many entries are in the HashMap
		System.out.println("\nNumber of Elements in HashMap="+stringHashMap.size());
		
		//See if the HashMap contains a specific key value (SUCCESS)
		if(stringHashMap.containsKey("SC"))
		{
			System.out.println("\nFound Key: SC");
		}

		
		System.out.println("----------------------------------------------------");
		
		//Create new HashMap that has key as integer and value as a String
		HashMap<Integer,String> integerHashMap = new HashMap<Integer,String>();
		
		//Add some values to our Integer HashMap
		integerHashMap.put(1, "One as a String");
		integerHashMap.put(2, "Two as a String");
		integerHashMap.put(3, "Three as a String");
	      
	    //Loop through HashMap to print out key/value pairs
		for (Map.Entry<Integer, String> myEntry : integerHashMap.entrySet()) 
		{
			System.out.println("Key="+myEntry.getKey()+" Value="+myEntry.getValue());
		}
		
		//Let's pull a value from HashMap using a specific key
		System.out.println("\n2 can be also be "+integerHashMap.get(2));
		
		//See how many entries are in the HashMap
		System.out.println("\nNumber of Elements in HashMap="+integerHashMap.size());
		
		//See if the HashMap contains a specific key value (SUCCESS)
		if(integerHashMap.containsKey(3))
		{
			System.out.println("\nFound Key: 3");
		}
	
	}

}


Sample Java HashMap Output:

Key=SC Value=South Carolina
Key=NC Value=North Carolina
Key=FL Value=Florida
Key=NY Value=New York

NC is short for North Carolina

Number of Elements in HashMap=4

Found Key: SC
----------------------------------------------------
Key=1 Value=One as a String
Key=2 Value=Two as a String
Key=3 Value=Three as a String

2 can be also be Two as a String

Number of Elements in HashMap=3

Found Key: 3



References:

Add a Comment

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