Java Programming Handbook

    Java HashMap

    Introduction#

    The HashMap class is one of the most commonly used data structures in Java, designed to store key-value pairs efficiently. It is a part of the java.util package and implements the Map interface.

    This blog will guide you through everything you need to know about HashMap, including its working mechanism, key methods, examples, internal performance considerations, and a conclusion.

    Java HashMap 

    Key Characteristics#

    • Implements the Map interface.
    • Stores data as key-value pairs.
    • Keys must be unique.
    • Allows one null key and multiple null values.
    • Does not maintain any insertion or sorted order.
    • Not synchronized (not thread-safe).

    HashMap Syntax#

    HashMap<K, V> map = new HashMap<>();

    Example:

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

    Commonly Used Methods in HashMap (With Examples and Output)#

    1. put(K key, V value) – Add or update key-value pair#

    Note:- Insertion order is not maintained here, To maintain insertion order use LinkedHashMap which we will see in our next blog.

    HashMap<String, String> map = new HashMap<>(); map.put("name", "John"); map.put("city", "New York"); map.put("name", "David"); // Updates the value for "name" System.out.println(map);

    Output:

    {name=David, city=New York}

    2. get(Object key) – Retrieve value for a key#

    String value = map.get("city"); System.out.println(value);

    Output:

    New York

    3. remove(Object key) – Remove mapping by key#

    map.remove("city"); System.out.println(map);

    Output:

    {name=David}

    4. containsKey(Object key) – Check if key exists#

    boolean exists = map.containsKey("name"); System.out.println(exists);

    Output:

    true

    5. containsValue(Object value) – Check if value exists#

    boolean hasValue = map.containsValue("David"); System.out.println(hasValue);

    Output:

    true

    6. size() – Total number of key-value pairs#

    int count = map.size(); System.out.println(count);

    Output:

    1

    7. isEmpty() – Check if map is empty#

    boolean empty = map.isEmpty(); System.out.println(empty);

    Output:

    false

    8. clear() – Remove all key-value pairs#

    map.clear(); System.out.println(map);

    Output:

    {}

    9. keySet() – Get all keys as a Set#

    map.put("name", "Alice"); map.put("city", "Delhi"); Set<String> keys = map.keySet(); System.out.println(keys);

    Output:

    [name, city]

    10. values() – Get all values as a Collection#

    Collection<String> values = map.values(); System.out.println(values);

    Output:

    [Alice, Delhi]

    11. entrySet() – Get all key-value pairs as a Set of Map.Entry#

    for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println(entry.getKey() + " => " + entry.getValue()); }

    Output:

    name => Alice city => Delhi

    Example: Basic HashMap Usage#

    import java.util.*; public class HashMapExample { public static void main(String[] args) { HashMap<Integer, String> map = new HashMap<>(); map.put(1, "Apple"); map.put(2, "Banana"); map.put(3, "Mango"); map.put(1, "Orange"); // Overwrites value for key 1 System.out.println("HashMap: " + map); } }

    Output:

    HashMap: {1=Orange, 2=Banana, 3=Mango}

    Example: Iterating through HashMap#

    HashMap<String, Integer> map = new HashMap<>(); map.put("Math", 90); map.put("Science", 85); map.put("English", 95); for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); }

    Output:

    Math: 90 Science: 85 English: 95

    Internal Working of HashMap#

    • Internally, HashMap uses an array of Node objects (buckets).
    • When you insert a key, it computes the hash code, which determines the bucket index.
    • If multiple keys map to the same index (collision), the entries are stored in a linked list or balanced tree (Java 8+).

    Performance and Time Complexity#

    OperationTime Complexity
    put()O(1) average, O(n) worst (due to collisions)
    get()O(1) average, O(n) worst
    remove()O(1) average, O(n) worst

    Note: From Java 8, when a bucket has more than 8 entries, the linked list is replaced by a balanced tree, improving worst-case time complexity to O(log n).

    When to Use HashMap#

    • When you need fast lookup and insertion.
    • When order of elements doesn’t matter.
    • When you can ensure only one thread is accessing the map (or use Collections.synchronizedMap() or ConcurrentHashMap).

    Conclusion#

    In this blog, we explored the HashMap class in Java in detail. We covered how it stores data in key-value pairs, its key methods with examples and outputs, how it works internally, performance characteristics, and when to use it in real-world applications.

    In the next blog, we will explore LinkedHashMap, which maintains the insertion order of key-value pairs while offering similar performance characteristics.

    Last updated on Apr 09, 2025