Java HashMap

Java HashMap

Java HashMap Implementation

Java HashMap Examples

Java HashMap vs HashTable

Java HashMap Interview Questions

What is a HashMap?

A HashMap is a data structure that lets you store data as key/value pairs:

HashMap people = new HashMap();
people.put("Sam", 45);
people.put("Brenda", 32);
people.get("Sam"); //returns 45

A HashMap is an implementation of the Map interface. The Map interface is part of the Java Collections framework. Java collections are data structures that let you store collections of data.

When should you use a HashMap?

Use a HashMap when you want to store and retrieve things based on keys. By associating unique keys with values, HashMap provides quick lookups and insertions. Using a HashMap allows you to lookup and insert values in near constant time (O(1)).

Unlike other collections like arrays, HashMap doesn't store elements in a particular order. If you want to keep track of the order in which elements are inserted you can use a LinkedHashMap or ArrayList instead.

While ordered lists have their benefits, HashMap is generally faster at retrieving and inserting elements especially as inputs grow. Traversing a list gets computationally more difficult as the number of elements increases (O(n)). This is not the case with a HashMap as infinitely more elements still results in constant lookup time based on unique keys ((0(1))).

Java HashMap Implementation

Underneath the hood, HashMap ultimately creates an array to store data. What makes HashMap faster is it's hashing mechanism where keys are hashed and indexed.

For more information check out Java HashMap Implementation

Java HashMap Examples

You've already seen one example of creating a HashMap:

HashMap people = new HashMap();
people.put("Sam", 45);
people.put("Brenda", 32);
people.get("Sam"); //returns 45

Remember that a HashMap is a set of key/value pairs. Notice how we specify the types for these values <String, Integer> as part of the definition. This example creates a map people where the keys are strings and the values are integers.

We add a key/value pair to the map via put(). We retrieve a value from the map via get().

For more examples of using HashMap, be sure to check our Java HashMap examples.

Java HashMap vs HashTable

A HashTable is similar to a HashMap. Data is stored as key/value pairs and accessed the same way. The key difference is HashTable is a synchronized version of HashMap meaning it is thread safe.

For more information on the difference between HashMap and HashTable check out Java HashMap vs HashTable.

Your thoughts?