Dung (Donny) Nguyen

Senior Software Engineer

HashMap

In Java, a HashMap is a part of the Java Collections Framework and provides an efficient way to store key-value pairs. It is part of the java.util package and implements the Map interface, which means it maps keys to values. Here are some key characteristics and features of a HashMap:

1. Key-Value Pair Storage

A HashMap stores data in key-value pairs. Each key is unique, but values can be duplicated. We can use keys to retrieve their corresponding values.

2. Hashing

HashMap uses a technique called hashing to store and retrieve elements efficiently. When a key is added to the map, it is hashed, and the resulting hash code determines the index in the array where the key-value pair is stored. This allows for average constant-time performance for get() and put() operations.

3. No Ordering

HashMap does not maintain any order of the keys or values. If we need to maintain the insertion order, we should use LinkedHashMap, and for sorting based on the keys, TreeMap is the right choice.

4. Null Keys and Values

HashMap allows one null key and multiple null values. However, having too many nulls might reduce the map’s efficiency.

5. Not Synchronized

HashMap is not thread-safe. If we need a synchronized (thread-safe) version, we can use Collections.synchronizedMap() to wrap the HashMap or use ConcurrentHashMap.

6. Performance

The time complexity for basic operations like get() and put() is generally O(1), assuming the hash function distributes keys evenly across the array. However, in the worst case (where all elements hash to the same bucket), it can degrade to O(n).

7. Internal Structure

HashMap uses an internal array of buckets, where each bucket is a LinkedList or a Tree (since Java 8). If the number of elements in a bucket exceeds a certain threshold, the bucket is transformed from a LinkedList to a Tree to improve search performance.

8. Load Factor and Capacity

HashMap has two key parameters:

Example Usage

import java.util.HashMap;

public class Example {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();

        // Adding elements to the map
        map.put("Apple", 10);
        map.put("Banana", 20);
        map.put("Orange", 30);

        // Retrieving a value by key
        System.out.println("Value for 'Apple': " + map.get("Apple"));

        // Checking if a key or value exists
        System.out.println("Contains 'Banana'?: " + map.containsKey("Banana"));

        // Iterating through the HashMap
        for (String key : map.keySet()) {
            System.out.println(key + ": " + map.get(key));
        }
    }
}

Common Operations

When to Use HashMap