Java Article 22 - Java Collections - HashMap

HashMaps are another variety of container (collection) object. They differ from other commonly used Java collection objects such as Arrays, ArrayLists, and LinkedLists in that they don't have indexes and their elements are not sorted. HashMaps implement the Map interface and not the List interface. HashMaps store their elements by a key. This is referred to as a key-value pair since the collection contains a key that is associated with a value (one of its elements).

Performance-wise HashMaps are very fast and are good for tasks such as looking up X if you know Y. I like to think of them as unordered lookup tables (the old-fashioned ones in an engineering reference book used to quickly find a density at a given temperature or enthalpy).

HashMaps are instantiated as other collection objects, but both the key and value types should be specified:

HashMap <String, String> products = HashMap <String, String> ();

You can also pass initial capacity and load factor as parameters which can be used to adjust memory and processor usage:

HashMap(int initialCapacity, float loadFactor)

You don't have to worry about too much about this for simple programs. Just remember the option is there if someday you need to optimize performance. The default load factor (no arguments) provides a balanced solution.

Also you can pass another Map object to create a new map with the same mappings:

HashMap(Map myMap)

So in a hypothetical business application you could have a product number as a key and the product name as the value. Strings are often used but another interesting application would be to use a string as a key and an object containing a variety of other data as a value.

Key-value pairs are added to HashMaps similar to other container objects except that instead of add(), the put() method is used, and both the key and value are passed as arguments:

products.put("1111", "low quality ham"); //product number and product name

products.get("1111"); //will return the product name associated with key 1111.

Today's program demonstrate some of HashMap's methods:

import java.util.*;

public class HashMapExample 
{

	static HashMap <String, String> products = 
		new HashMap <String, String> ();
		
	public static void main(String[] argv)
	{
		
		demonstratePut();
		demonstrateView();
		demonstrateIterate();
		demonstrateContains();
		demonstrateRemove();
		
	}


	private static void demonstratePut() 
	{
		
		System.out.print("Here we add some key-value pairs to " +
				"our HashMap with put():");
		
		products.put("1111a", "Low Quality Ham");
		products.put("1112f", "Medium Quality Ham");
		products.put("1113m", "High Quality Ham");
		products.put("1114z", "Radioactive Ham");
		displayCollection();
		System.out.print("\nNotice they are not in the " +
				"same order added");
		
	}
	
	
	
	private static void displayCollection() 
	{
		//The contents of many collection objects can be 
		//printed simply by:
		System.out.print("\nproducts contents: " + products);
		
	}
	
	private static void demonstrateView() 
	{
		System.out.println("\n\nOther ways of viewing key " +
				"& values:");
		System.out.println("entrySet(): " + products.entrySet());
		System.out.println("keySet(): " + products.keySet());
		System.out.println("values(): " + products.values());
		System.out.println("get(\"1111a\"): " 
				+ products.get("1111a"));
		System.out.println("get() will return null if the " +
				"key-value pair is not present:");
		System.out.println("get(\"XXXX\"): " 
				+ products.get("XXXX"));
		
	}
	
	
	 // While not as straightforward as other collection classes
	 // you can still iterate though a HashMap:
	 
	private static void demonstrateIterate() 
	{
		
		System.out.println("\nIteration examples: ");
		//using for-each and keySet()
		for (String key : products.keySet())
		{
			System.out.println(key);
		}
		System.out.println();
		//using for-each and Map.Entry
		for (Map.Entry e : products.entrySet())
		{
		    System.out.println(e.getKey() + ": " + e.getValue());
		}
	}
	
	private static void demonstrateContains() 
	{
		System.out.println("\nTesting for keys and values:");
		System.out.println("containsKey(\"1111a\"): " 
				+ products.containsKey("1111a"));
		
		System.out.println("containsValue(\"Radioactive Ham\"): " 
				+ products.containsValue("Radioactive Ham"));
		
	}

	private static void demonstrateRemove() 
	{
		System.out.println("\nproducts.remove(\"1114z\") removes " +
				"this key. The value is then inacesseable:");
		
		products.remove("1114z");
		displayCollection();
		
	}
}