Java - HashMap and TreeMap

Java HashMap and TreeMap – Complete Notes

 HashMap and TreeMap in Java

Java provides powerful Map-based data structures used widely for storing key-value pairs efficiently. Among these, HashMap and TreeMap are the two most commonly used Map implementations inside the java.util package. They help developers store, organize, search, and retrieve data extremely fast. These collections are heavily used in real-world Java applications such as caching, indexing, database mapping, storing configurations, user sessions, collections of unique keys, and grouping data. This document explains HashMap and TreeMap with complete clarity, SEO-rich keywords, deep explanations, code samples, outputs, and conceptual notes that help students, beginners, and advanced Java learners understand every detail from scratch to professional-level depth.

What is a HashMap in Java?

A HashMap in Java is a popular implementation of the Map interface. It stores data in the form of key-value pairs. Unlike List or Set, a HashMap does not maintain the insertion order. Instead, it uses hashing (through the hashCode method) internally to store the values. HashMap allows one null key and multiple null values. It works on the principle of buckets, hashing, and linked lists or balanced trees depending on the number of collisions. It is designed for performance, making retrieval and insertion operations average O(1). Because of its efficiency, HashMap is widely used in web applications, frameworks like Spring, caching mechanisms, compiler symbol tables, and storing user sessions. Understanding HashMap is important for any Java developer because it represents the foundation of high-performance Java development.

Characteristics of HashMap

HashMap comes with several important characteristics that make it extremely efficient and suitable for modern Java applications. It does not maintain any order of its elements. The hashing mechanism calculates the hash code of the key to determine the index where the key-value pair will be stored. When more than one key hashes to the same bucket, HashMap uses a linked list or a balanced tree structure to resolve collisions. HashMap is not synchronized, meaning it is not thread-safe by default. If multiple threads modify it simultaneously without external synchronization, data inconsistency may occur. HashMap offers constant-time complexity for basic operations such as add, get, and remove, making it one of the fastest data structures in Java. Internally, it uses an array of buckets and distributes keys evenly using the hashing algorithm to avoid collisions.

Creating and Using a HashMap

Creating a HashMap in Java is very simple. It can store any type of keys and values. Developers must ensure that the keys implement proper hashCode and equals methods to ensure correct behavior. The following example demonstrates how to create a HashMap, add key-value pairs, retrieve values, and display the output. This helps beginners understand how HashMap works in real Java programs. Every operation in the example reflects real-world use cases, such as storing employee data, product details, or configuration settings.

Example: Basic HashMap Program


import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {

        HashMap map = new HashMap<>();

        map.put(1, "Apple");
        map.put(2, "Banana");
        map.put(3, "Cherry");

        System.out.println("HashMap Elements: " + map);
        System.out.println("Value at key 2: " + map.get(2));

        map.remove(3);
        System.out.println("After removing key 3: " + map);
    }
}

Output:


HashMap Elements: {1=Apple, 2=Banana, 3=Cherry}
Value at key 2: Banana
After removing key 3: {1=Apple, 2=Banana}

Internal Working of HashMap

The internal working of HashMap is one of the most frequently asked concepts in Java interviews. When a key is inserted, Java calculates its hash code. This hash code is then converted into a bucket index, which determines where the entry will be stored in the internal array. If two keys generate the same bucket index, a collision occurs. HashMap uses a linked list or a balanced tree (introduced in Java 8) to manage collisions. When entries in a bucket exceed a threshold, Java converts the linked list into a Red-Black tree to improve performance. During retrieval, the hash code is used first followed by equals method to locate the exact key. Understanding this mechanism helps developers write optimized and collision-resistant code.

What is a TreeMap in Java?

TreeMap is another implementation of the Map interface in Java but unlike HashMap, TreeMap stores elements in a sorted order based on the natural ordering of keys or a custom Comparator. Internally, TreeMap uses a self-balancing Red-Black Tree. Every time you add a key-value pair, TreeMap places it in its sorted position. TreeMap does not allow null keys but permits null values. It is slower than HashMap because it requires additional time to maintain sorting, with operations having O(log n) complexity. TreeMap is ideal when you need sorted data such as alphabetical lists, leaderboard ranking, sorted logs, or numerical ranges. Because of its ordering capability, TreeMap is preferred in applications involving searching, navigation, and range queries.

Characteristics of TreeMap

TreeMap maintains a strictly sorted structure based on natural order or custom Comparator logic. It implements NavigableMap, which provides methods like higherKey, lowerKey, firstEntry, and lastEntry that are extremely useful in range-based operations. It does not allow null keys because comparing null with other keys would cause an exception. TreeMap guarantees predictable iteration order, which is highly useful in scenarios such as generating reports, sorted data outputs, or leaderboard rankings. All operations such as add, remove, search take O(log n) time due to tree rebalancing. Its sorted behavior and navigation methods make TreeMap one of the most powerful data structures for ordered data handling in Java.

Creating and Using a TreeMap

Creating and using a TreeMap is similar to HashMap but with sorting capabilities. Developers often use it when they require keys in sorted order. The example below demonstrates how to create a TreeMap, insert key-value pairs, retrieve data, and observe the sorted nature of TreeMap. This helps programmers understand the differences between HashMap and TreeMap in real-world scenarios.

Example: Basic TreeMap Program


import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {

        TreeMap map = new TreeMap<>();

        map.put(30, "Laptop");
        map.put(10, "Keyboard");
        map.put(20, "Mouse");

        System.out.println("TreeMap Elements: " + map);
        System.out.println("First Key: " + map.firstKey());
        System.out.println("Last Key: " + map.lastKey());
    }
}

Output:


TreeMap Elements: {10=Keyboard, 20=Mouse, 30=Laptop}
First Key: 10
Last Key: 30

Internal Working of TreeMap

TreeMap works using a Red-Black tree, which is a self-balancing binary search tree. Every time you insert a key-value pair, TreeMap compares the key with the root and decides whether to move left or right. If the new key is smaller, it goes to the left subtree, and if larger, to the right. After insertion or removal, the tree reorganizes itself to maintain balance. This balancing ensures that operations remain efficient and perform consistently in O(log n) time. Because of sorting and self-balancing, TreeMap is widely used in applications requiring predictable ordering and fast navigation between keys.

Difference Between HashMap and TreeMap

Although both HashMap and TreeMap implement the Map interface, they serve different purposes. HashMap is used when fast performance is required without caring about the order of keys. TreeMap is ideal when sorted output is necessary. HashMap gives average constant-time performance, while TreeMap gives logarithmic-time performance. HashMap allows null keys, but TreeMap does not. TreeMap’s sorted nature makes it suitable for range queries, while HashMap excels in fast lookups. Developers often choose between them based on whether order or speed is more important.

Example Code: Demonstrating Differences


import java.util.HashMap;
import java.util.TreeMap;

public class MapComparison {
    public static void main(String[] args) {

        HashMap hashMap = new HashMap<>();
        hashMap.put(3, "Red");
        hashMap.put(1, "Blue");
        hashMap.put(2, "Green");

        TreeMap treeMap = new TreeMap<>();
        treeMap.put(3, "Red");
        treeMap.put(1, "Blue");
        treeMap.put(2, "Green");

        System.out.println("HashMap Output: " + hashMap);
        System.out.println("TreeMap Output: " + treeMap);
    }
}

Output:


HashMap Output: {1=Blue, 2=Green, 3=Red}  (unordered)
TreeMap Output: {1=Blue, 2=Green, 3=Red}  (sorted)

When to Use HashMap and When to Use TreeMap

Use HashMap when speed is the priority and ordering does not matter. It is ideal for caching, lookups, storing configurations, or processing large amounts of data quickly. Use TreeMap when a sorted output is needed such as sorted logs, alphabetically ordered lists, maintaining leaderboard rankings, or implementing range-based searches. Understanding the appropriate use case helps developers write efficient, scalable, and performance-optimized applications.


In conclusion, both HashMap and TreeMap are essential data structures in Java that help developers manage key-value pairs efficiently in real-world applications. HashMap is the best choice when high performance, fast lookups, and large-scale data processing are required without caring about the order of elements. Its average O(1) complexity for insertion and retrieval makes it one of the most powerful collections for performance-critical applications such as caching, session management, configuration storage, and rapid data access. On the other hand, TreeMap maintains natural sorting of keys and guarantees predictable ordering. This makes TreeMap highly suitable for applications such as leaderboards, sorted logs, alphabetical indexes, and range-based queries where organized and structured data output is important.

Both data structures have unique strengths, and the correct choice depends on the requirement of ordering vs performance. Developers must also consider restrictions like null key allowance in HashMap but not in TreeMap, the difference in time complexity, and how data will be accessed or navigated. By understanding their internal working principlesβ€”hashing for HashMap and Red-Black tree balancing for TreeMapβ€”Java programmers can design more efficient, scalable, and optimized solutions. Mastery of these two Map implementations greatly improves the ability to write clean, fast, and well-structured Java applications that follow best practices and industry standards.

logo

Java

Beginner 5 Hours
Java HashMap and TreeMap – Complete Notes

 HashMap and TreeMap in Java

Java provides powerful Map-based data structures used widely for storing key-value pairs efficiently. Among these, HashMap and TreeMap are the two most commonly used Map implementations inside the java.util package. They help developers store, organize, search, and retrieve data extremely fast. These collections are heavily used in real-world Java applications such as caching, indexing, database mapping, storing configurations, user sessions, collections of unique keys, and grouping data. This document explains HashMap and TreeMap with complete clarity, SEO-rich keywords, deep explanations, code samples, outputs, and conceptual notes that help students, beginners, and advanced Java learners understand every detail from scratch to professional-level depth.

What is a HashMap in Java?

A HashMap in Java is a popular implementation of the Map interface. It stores data in the form of key-value pairs. Unlike List or Set, a HashMap does not maintain the insertion order. Instead, it uses hashing (through the hashCode method) internally to store the values. HashMap allows one null key and multiple null values. It works on the principle of buckets, hashing, and linked lists or balanced trees depending on the number of collisions. It is designed for performance, making retrieval and insertion operations average O(1). Because of its efficiency, HashMap is widely used in web applications, frameworks like Spring, caching mechanisms, compiler symbol tables, and storing user sessions. Understanding HashMap is important for any Java developer because it represents the foundation of high-performance Java development.

Characteristics of HashMap

HashMap comes with several important characteristics that make it extremely efficient and suitable for modern Java applications. It does not maintain any order of its elements. The hashing mechanism calculates the hash code of the key to determine the index where the key-value pair will be stored. When more than one key hashes to the same bucket, HashMap uses a linked list or a balanced tree structure to resolve collisions. HashMap is not synchronized, meaning it is not thread-safe by default. If multiple threads modify it simultaneously without external synchronization, data inconsistency may occur. HashMap offers constant-time complexity for basic operations such as add, get, and remove, making it one of the fastest data structures in Java. Internally, it uses an array of buckets and distributes keys evenly using the hashing algorithm to avoid collisions.

Creating and Using a HashMap

Creating a HashMap in Java is very simple. It can store any type of keys and values. Developers must ensure that the keys implement proper hashCode and equals methods to ensure correct behavior. The following example demonstrates how to create a HashMap, add key-value pairs, retrieve values, and display the output. This helps beginners understand how HashMap works in real Java programs. Every operation in the example reflects real-world use cases, such as storing employee data, product details, or configuration settings.

Example: Basic HashMap Program

import java.util.HashMap; public class HashMapExample { public static void main(String[] args) { HashMap map = new HashMap<>(); map.put(1, "Apple"); map.put(2, "Banana"); map.put(3, "Cherry"); System.out.println("HashMap Elements: " + map); System.out.println("Value at key 2: " + map.get(2)); map.remove(3); System.out.println("After removing key 3: " + map); } }

Output:

HashMap Elements: {1=Apple, 2=Banana, 3=Cherry} Value at key 2: Banana After removing key 3: {1=Apple, 2=Banana}

Internal Working of HashMap

The internal working of HashMap is one of the most frequently asked concepts in Java interviews. When a key is inserted, Java calculates its hash code. This hash code is then converted into a bucket index, which determines where the entry will be stored in the internal array. If two keys generate the same bucket index, a collision occurs. HashMap uses a linked list or a balanced tree (introduced in Java 8) to manage collisions. When entries in a bucket exceed a threshold, Java converts the linked list into a Red-Black tree to improve performance. During retrieval, the hash code is used first followed by equals method to locate the exact key. Understanding this mechanism helps developers write optimized and collision-resistant code.

What is a TreeMap in Java?

TreeMap is another implementation of the Map interface in Java but unlike HashMap, TreeMap stores elements in a sorted order based on the natural ordering of keys or a custom Comparator. Internally, TreeMap uses a self-balancing Red-Black Tree. Every time you add a key-value pair, TreeMap places it in its sorted position. TreeMap does not allow null keys but permits null values. It is slower than HashMap because it requires additional time to maintain sorting, with operations having O(log n) complexity. TreeMap is ideal when you need sorted data such as alphabetical lists, leaderboard ranking, sorted logs, or numerical ranges. Because of its ordering capability, TreeMap is preferred in applications involving searching, navigation, and range queries.

Characteristics of TreeMap

TreeMap maintains a strictly sorted structure based on natural order or custom Comparator logic. It implements NavigableMap, which provides methods like higherKey, lowerKey, firstEntry, and lastEntry that are extremely useful in range-based operations. It does not allow null keys because comparing null with other keys would cause an exception. TreeMap guarantees predictable iteration order, which is highly useful in scenarios such as generating reports, sorted data outputs, or leaderboard rankings. All operations such as add, remove, search take O(log n) time due to tree rebalancing. Its sorted behavior and navigation methods make TreeMap one of the most powerful data structures for ordered data handling in Java.

Creating and Using a TreeMap

Creating and using a TreeMap is similar to HashMap but with sorting capabilities. Developers often use it when they require keys in sorted order. The example below demonstrates how to create a TreeMap, insert key-value pairs, retrieve data, and observe the sorted nature of TreeMap. This helps programmers understand the differences between HashMap and TreeMap in real-world scenarios.

Example: Basic TreeMap Program

import java.util.TreeMap; public class TreeMapExample { public static void main(String[] args) { TreeMap map = new TreeMap<>(); map.put(30, "Laptop"); map.put(10, "Keyboard"); map.put(20, "Mouse"); System.out.println("TreeMap Elements: " + map); System.out.println("First Key: " + map.firstKey()); System.out.println("Last Key: " + map.lastKey()); } }

Output:

TreeMap Elements: {10=Keyboard, 20=Mouse, 30=Laptop} First Key: 10 Last Key: 30

Internal Working of TreeMap

TreeMap works using a Red-Black tree, which is a self-balancing binary search tree. Every time you insert a key-value pair, TreeMap compares the key with the root and decides whether to move left or right. If the new key is smaller, it goes to the left subtree, and if larger, to the right. After insertion or removal, the tree reorganizes itself to maintain balance. This balancing ensures that operations remain efficient and perform consistently in O(log n) time. Because of sorting and self-balancing, TreeMap is widely used in applications requiring predictable ordering and fast navigation between keys.

Difference Between HashMap and TreeMap

Although both HashMap and TreeMap implement the Map interface, they serve different purposes. HashMap is used when fast performance is required without caring about the order of keys. TreeMap is ideal when sorted output is necessary. HashMap gives average constant-time performance, while TreeMap gives logarithmic-time performance. HashMap allows null keys, but TreeMap does not. TreeMap’s sorted nature makes it suitable for range queries, while HashMap excels in fast lookups. Developers often choose between them based on whether order or speed is more important.

Example Code: Demonstrating Differences

import java.util.HashMap; import java.util.TreeMap; public class MapComparison { public static void main(String[] args) { HashMap hashMap = new HashMap<>(); hashMap.put(3, "Red"); hashMap.put(1, "Blue"); hashMap.put(2, "Green"); TreeMap treeMap = new TreeMap<>(); treeMap.put(3, "Red"); treeMap.put(1, "Blue"); treeMap.put(2, "Green"); System.out.println("HashMap Output: " + hashMap); System.out.println("TreeMap Output: " + treeMap); } }

Output:

HashMap Output: {1=Blue, 2=Green, 3=Red} (unordered) TreeMap Output: {1=Blue, 2=Green, 3=Red} (sorted)

When to Use HashMap and When to Use TreeMap

Use HashMap when speed is the priority and ordering does not matter. It is ideal for caching, lookups, storing configurations, or processing large amounts of data quickly. Use TreeMap when a sorted output is needed such as sorted logs, alphabetically ordered lists, maintaining leaderboard rankings, or implementing range-based searches. Understanding the appropriate use case helps developers write efficient, scalable, and performance-optimized applications.


In conclusion, both HashMap and TreeMap are essential data structures in Java that help developers manage key-value pairs efficiently in real-world applications. HashMap is the best choice when high performance, fast lookups, and large-scale data processing are required without caring about the order of elements. Its average O(1) complexity for insertion and retrieval makes it one of the most powerful collections for performance-critical applications such as caching, session management, configuration storage, and rapid data access. On the other hand, TreeMap maintains natural sorting of keys and guarantees predictable ordering. This makes TreeMap highly suitable for applications such as leaderboards, sorted logs, alphabetical indexes, and range-based queries where organized and structured data output is important.

Both data structures have unique strengths, and the correct choice depends on the requirement of ordering vs performance. Developers must also consider restrictions like null key allowance in HashMap but not in TreeMap, the difference in time complexity, and how data will be accessed or navigated. By understanding their internal working principles—hashing for HashMap and Red-Black tree balancing for TreeMap—Java programmers can design more efficient, scalable, and optimized solutions. Mastery of these two Map implementations greatly improves the ability to write clean, fast, and well-structured Java applications that follow best practices and industry standards.

Related Tutorials

Frequently Asked Questions for Java

Java is known for its key features such as object-oriented programming, platform independence, robust exception handling, multithreading capabilities, and automatic garbage collection.

The Java Development Kit (JDK) is a software development kit used to develop Java applications. The Java Runtime Environment (JRE) provides libraries and other resources to run Java applications, while the Java Virtual Machine (JVM) executes Java bytecode.

Java is a high-level, object-oriented programming language known for its platform independence. This means that Java programs can run on any device that has a Java Virtual Machine (JVM) installed, making it versatile across different operating systems.

Deadlock is a situation in multithreading where two or more threads are blocked forever, waiting for each other to release resources.

Functional programming in Java involves writing code using functions, immutability, and higher-order functions, often utilizing features introduced in Java 8.

A process is an independent program in execution, while a thread is a lightweight subprocess that shares resources with other threads within the same process.

The Comparable interface defines a natural ordering for objects, while the Comparator interface defines an external ordering.

The List interface allows duplicate elements and maintains the order of insertion, while the Set interface does not allow duplicates and does not guarantee any specific order.

String is immutable, meaning its value cannot be changed after creation. StringBuffer and StringBuilder are mutable, allowing modifications to their contents. The main difference between them is that StringBuffer is synchronized, making it thread-safe, while StringBuilder is not.

Checked exceptions are exceptions that must be either caught or declared in the method signature, while unchecked exceptions do not require explicit handling.

ArrayList is backed by a dynamic array, providing fast random access but slower insertions and deletions. LinkedList is backed by a doubly-linked list, offering faster insertions and deletions but slower random access.

Autoboxing is the automatic conversion between primitive types and their corresponding wrapper classes. For example, converting an int to Integer.

The 'synchronized' keyword in Java is used to control access to a method or block of code by multiple threads, ensuring that only one thread can execute it at a time.

Multithreading in Java allows concurrent execution of two or more threads, enabling efficient CPU utilization and improved application performance.

A HashMap is a collection class that implements the Map interface, storing key-value pairs. It allows null values and keys and provides constant-time performance for basic operations.

Java achieves platform independence by compiling source code into bytecode, which is executed by the JVM. This allows Java programs to run on any platform that has a compatible JVM.

The Serializable interface provides a default mechanism for serialization, while the Externalizable interface allows for custom serialization behavior.

The 'volatile' keyword in Java indicates that a variable's value will be modified by multiple threads, ensuring that the most up-to-date value is always visible.

Serialization is the process of converting an object into a byte stream, enabling it to be saved to a file or transmitted over a network.

The finalize() method is called by the garbage collector before an object is destroyed, allowing for cleanup operations.

The 'final' keyword in Java is used to define constants, prevent method overriding, and prevent inheritance of classes, ensuring that certain elements remain unchanged.

Garbage collection is the process by which the JVM automatically deletes objects that are no longer reachable, freeing up memory resources.

'throw' is used to explicitly throw an exception, while 'throws' is used in method declarations to specify that a method can throw one or more exceptions.

The 'super' keyword in Java refers to the immediate parent class and is used to access parent class methods, constructors, and variables.

The JVM is responsible for loading, verifying, and executing Java bytecode. It provides an abstraction between the compiled Java program and the underlying hardware, enabling platform independence.

line

Copyrights © 2024 letsupdateskills All rights reserved