Java Lesson 35 – HashMap | Dataplexa

HashMap

A HashMap is one of the most powerful and widely used data structures in Java. It stores data in the form of key–value pairs.

Instead of accessing data using an index (like lists), HashMap allows you to retrieve values instantly using a unique key.


Why HashMap is Important

In real-world applications, data is rarely accessed by position. It is usually accessed by an identifier.

Examples:

  • User ID → User details
  • Product code → Product information
  • Username → Account settings
  • Email → Profile data

HashMap is designed exactly for these use cases.


Key Characteristics of HashMap

  • Stores data as key–value pairs
  • Keys must be unique
  • Values can be duplicated
  • Does not maintain insertion order
  • Very fast data retrieval

Creating a HashMap

HashMap belongs to the java.util package and implements the Map interface.


import java.util.HashMap;
import java.util.Map;

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

        Map students = new HashMap<>();

        students.put(101, "Alice");
        students.put(102, "Bob");
        students.put(103, "Charlie");

        System.out.println(students);
    }
}

Adding and Updating Data

You add data using the put() method. If a key already exists, the value gets updated.


students.put(102, "Robert");   // updates value
students.put(104, "Diana");   // adds new entry

System.out.println(students);

Accessing Values

You retrieve values using the key with the get() method.


System.out.println(students.get(101));
System.out.println(students.get(104));

If the key does not exist, null is returned.


Removing Entries

Entries can be removed easily using the remove() method.


students.remove(103);

System.out.println(students);

Iterating Over a HashMap

You can loop through a HashMap using keys, values, or both.


for (Map.Entry entry : students.entrySet()) {
    System.out.println(entry.getKey() + " -> " + entry.getValue());
}

Real-World Example

Consider storing product prices in an online store.


Map productPrices = new HashMap<>();

productPrices.put("Laptop", 1200.00);
productPrices.put("Phone", 800.00);
productPrices.put("Tablet", 450.00);

System.out.println("Laptop price: " + productPrices.get("Laptop"));

Using HashMap makes lookup fast and code readable.


HashMap vs LinkedList

  • LinkedList – ordered, sequential access
  • HashMap – unordered, key-based access

They serve completely different purposes.


When to Use HashMap

  • When data is accessed by a unique key
  • When fast search is required
  • When order does not matter

Key Takeaways

  • HashMap stores key–value pairs
  • Keys are unique, values can repeat
  • Provides very fast lookup
  • Widely used in real-world Java applications

In the next lesson, we will explore Iterators and learn how to safely traverse collections.