Java Collections – HashMap Example
The HashMap is a hash table based implementation of the map interface and represents a mapping between a key and a value. A HashMap is roughly equivalent to HashTable except that it permits nulls and is unsynchronized. In the example I have detailed, it will represent a mapping of the employee’s name and their yearly salary.
Big-O Notation
According to the Javadocs, this implementation provides constant-time O(1) performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets.
Creating a HashMap
This was the old-way prior to Generics.
Map employees = new HashMap();
Generics
If you look closely, you will notice that I am using Generics to limit the type to String for the Key, and Integer for the Value in the Map. Generics add stability to your code, by having the computer detect type incompatibilities during compile-time. These runtime bugs would be more difficult to debug if left unchecked.
Map<String,Integer> employees = new HashMap<String,Integer>();
Adding elements
Adding elements to the employees Map is done by using the put(Object key, Object value) method. The key of the Map will be the employee name which is a String and the value will be an Integer object. But wait? We are passing an Integer object we are passing an int primitive and Java is not complaining and we did not have to use new Integer(…). Why is this working?
Auto-Boxing and Unboxing
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer and vice-versa without the need to cast. In this case, Java is performing the boxing when we put elements into the map (converting int to Integer wrapper class) and unboxing when we get() elements from the Map (converting Integer to int primitive).
employees.put("John Smith", 85000); employees.put("David Harvey", 53000); employees.put("James Young", 103500); employees.put("Danielle Gray", 94250); employees.put("Jeff Wang", 76500); employees.put("Chris Canning", 150000); employees.put("Mary Anderson", 104100); employees.put("Tina Mayer", 143700);
Removing elements
Removing elements is just a matter of calling the remove(Object key) method.
employees.remove("Jeff Wang"); employees.remove("Mary Anderson");
Size of Collection
Returning the number of elements in a HashMap is as easy as calling the size() method.
employees.size();
Iterating through the Collection
Java 1.5 and above provides a foreach loop, which makes it much easier to iterate over the entire collection. This is my preferred way of doing it.
// Loop through the collection of employees for (String name : employees.keySet()) { // Get the salary by passing the employee name as the key,
the salary is Auto-UnBoxed int salary = employees.get(name); }
Iterating through the Collection with Generics
Map<String,Integer> employees = new HashMap<String,Integer>(); Iterator iterator = employees.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String,Integer> element = (Map.Entry) iterator.next(); String name = element.getKey(); int salary = element.getValue(); System.out.format("Employee==> %-14s | %8dn", name, salary); }
Iterating through the Collection without Generics
Map employees = new HashMap(); Iterator iterator = employees.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry element = (Map.Entry) iterator.next(); String name = (String) element.getKey(); int salary = ((Integer)element.getValue()).intValue(); System.out.format("Employee==> %-14s | %8dn", name, salary); }
Please Note
Using a HashMap does not guarantee the order of the elements. It also makes no guarantee that the order will remain constant.
Full Program Listing
package com.avaldes.tutorials; import java.util.HashMap; import java.util.Map; public class HashMapExample { public static void main(String[] args) { // Ensure that the hashmap only takes String for the key and // Integer for the value Map<String,Integer> employees = new HashMap<String,Integer>(); // Populate the employee hashmap -- Auto-Boxing employees.put("John Smith", 85000); employees.put("David Harvey", 53000); employees.put("James Young", 103500); employees.put("Danielle Gray", 94250); employees.put("Jeff Wang", 76500); employees.put("Chris Canning", 150000); employees.put("Mary Anderson", 104100); employees.put("Tina Mayer", 143700); System.out.println("Display All Employees -- prior to delete operation"); displayAllEmployees(employees); System.out.println("Number of Employees: " + employees.size()); // Let's remove employee Jeff Wang & Mary Anderson System.out.println("Removing Jeff Wang from employees"); employees.remove("Jeff Wang"); System.out.println("Removing Mary Anderson from employeesn"); employees.remove("Mary Anderson"); System.out.println("Display All Employees -- after delete operation"); displayAllEmployees(employees); System.out.println("Number of Employees: " + employees.size()); } static public void displayAllEmployees(Map<String,Integer> employees) { int count = 0; // Loop through the collection of employees for (String name : employees.keySet()) { count++; // Get the salary by passing the employee name as the key, the // salary is Auto-UnBoxed int salary = employees.get(name); // Format the output nicely System.out.format("Employee==> [%d] %-14s | %8dn", count,name,salary); } } }
Output

Display All Employees -- prior to delete operation Employee==> [1] David Harvey | 53000 Employee==> [2] Tina Mayer | 143700 Employee==> [3] Chris Canning | 150000 Employee==> [4] Mary Anderson | 104100 Employee==> [5] Jeff Wang | 76500 Employee==> [6] John Smith | 85000 Employee==> [7] Danielle Gray | 94250 Employee==> [8] James Young | 103500 Number of Employees: 8 Removing Jeff Wang from employees Removing Mary Anderson from employees Display All Employees -- after delete operation Employee==> [1] David Harvey | 53000 Employee==> [2] Tina Mayer | 143700 Employee==> [3] Chris Canning | 150000 Employee==> [4] John Smith | 85000 Employee==> [5] Danielle Gray | 94250 Employee==> [6] James Young | 103500 Number of Employees: 6
Other Related Posts
Map Examples
- Hashtable Example
Simple example shows you step by step how to use Hashtable - HashMap Example
Simple example shows you step by step how to use HashMap - TreeMap Example
Simple example shows you step by step how to use TreeMap to sort a collection - EnumMap Example
Simple example shows you step by step how to use EnumMap for type-safety and speed of finite list of elements - WeakHashMap Example
Simple example shows you step by step how to use WeakHashMap - LinkedHashMap Example
Simple example shows you step by step how to use LinkedHashMap - Performance Comparison HashMap vs Hashtable vs TreeMap
Performance Comparison - Performance Comparison HashMap vs Hashtable vs TreeMap Benchmark Test
List Examples
- Stack Example
Simple example shows you step by step how to use Stack - Vector Example
Simple example shows you step by step how to use Vector - LinkedList Example
Simple example shows you step by step how to use LinkedList - ArrayList Example
Simple example shows you step by step how to use ArrayList - Performance Comparison between the four list implementations
Performance Comparison of ArrayList, LinkedList, Vector, and Stack - Performance Comparison ArrayList vs LinkedList
Performance Comparison - ArrayList vs LinkedList
Set Examples
- BitSet Example
Simple example shows you step by step how to use BitSet - EnumSet Example
Simple example shows you step by step how to use EnumSet - HashSet Example
Simple example shows you step by step how to use HashSet - TreeSet Example
Simple example shows you step by step how to use TreeSet - LinkedHashSet Example
Simple example shows you step by step how to use LinkedHashSet
Please Share Us on Social Media






Leave a Reply