What is a HashMap in Java?

What is HashMap?

A HashMap is a powerful data structure that stores data in key-value pairs. It is a part of the Java Collections Framework and is found inside the java.util package.

It is a part of the Java Collections Framework and is found inside the java.util package.

Think of a HashMap as a kind of digital dictionary, just like how you search for a word (key) and find its meaning (value), and it also allows you to store and quickly retrieve data using a key.

Each key in a HashMap is unique, and each key is mapped to exactly one value. If you try to insert another value using an already existing key, the old value will be replaced with the new one.

Why Use a HashMap in Java?

HashMap is one of the fastest and most convenient ways to store and manage data in key-value form.

  • Fast Access: HashMap provides constant-time performance for basic operations like adding (put()), retrieving (get()), or removing (remove()) elements. That means even if your HashMap has thousands of entries, you can still find or update an element almost instantly.
  • No Duplicate Keys: A HashMap automatically ensures that no two keys are the same. If you insert a new value with an existing key, it will replace the old value.
  • Flexible Storage: HashMap supports generic types, so you can store almost any combination of key and value pairs:
    • HashMap<String, String> → Store names and cities
    • HashMap<Integer, String> → Store roll numbers and names
    • HashMap<String, Double> → Store product names and prices
  • Real-World Usage: HashMaps are used everywhere in software systems, such as caching data for faster access, storing user sessions in web applications, keeping key-value pairs like “username → password hash”, and counting word frequencies in a document.

How Does a HashMap Work?

A HashMap uses an internal array of “buckets” to store data. When you insert a key-value pair:

  • Java calculates a hash code from the key using a hashing function.
  • That hash code decides which bucket (index) the data should go into.
  • If two keys have the same hash code (called a collision), Java handles it by using a small linked list or tree inside that bucket.

When you later search for a key using the get() method, Java again:

  • Computes the hash code,
  • Finds the correct bucket, and
  • Retrieves the value directly

Syntax to Create a HashMap

Map<KeyType, ValueType> map = new HashMap<>();
  • KeyType → Type of the key (e.g., Integer, String)
  • ValueType → Type of the value (e.g., String, Double)

Example: Creating and Using a HashMap of Integer Keys and String Values

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

public class FruitStore {
public static void main(String[] args) {
// Creating a HashMap to store fruit IDs and their names
Map<Integer, String> fruits = new HashMap<>();

// Adding key-value pairs to the HashMap
fruits.put(101, "Apple");
fruits.put(102, "Banana");
fruits.put(103, "Cherry");
fruits.put(104, "Mango");

// Printing the entire HashMap
System.out.println("Available Fruits: " + fruits);

// Accessing a specific fruit using its key
System.out.println("Fruit with ID 102: " + fruits.get(102));

// Updating a value for an existing key
fruits.put(103, "Watermelon");
System.out.println("After Updating: " + fruits);

// Removing a fruit using its key
fruits.remove(101);
System.out.println("After Removing Key 101: " + fruits);
}
}

Output:

Available Fruits: {101=Apple, 102=Banana, 103=Cherry, 104=Mango}
Fruit with ID 102: Banana
After Updating: {101=Apple, 102=Banana, 103=Watermelon, 104=Mango}
After Removing Key 101: {102=Banana, 103=Watermelon, 104=Mango}

Common Operations in HashMap

A HashMap is not only useful for storing key-value pairs, but it also provides several built-in methods to manage and manipulate data.

  1. put(K key, V value): It adds a key-value pair to the map. If the key already exists, the old value is replaced with the new value.
  2. get(Object key): Retrieves the value associated with the key.
  3. remove(Object key): Removes the key-value pair associated with the given key.
  4. containsKey(Object key): Checks if the map contains the specified key.
  5. size(): Returns the number of key-value pairs in the map.
  6. clear(): Removes all entries from the map, leaving it empty.

Example: Using Common HashMap Methods

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

public class StudentGrades {
public static void main(String[] args) {
// Creating a HashMap to store student IDs and their grades
Map<Integer, String> grades = new HashMap<>();

// Adding students and their grades
grades.put(101, "A");
grades.put(102, "B");
grades.put(103, "C");

// Retrieving a grade for a specific student
System.out.println("Grade for Student 102: " + grades.get(102));

// Checking if a student exists in the map
System.out.println("Does Student 103 exist? " + grades.containsKey(103));

// Updating a grade
grades.put(103, "B+");
System.out.println("Updated Grades: " + grades);

// Removing a student from the map
grades.remove(101);
System.out.println("After Removing Student 101: " + grades);

// Checking the number of students in the map
System.out.println("Total Students: " + grades.size());

// Clearing all data
grades.clear();
System.out.println("After Clearing: " + grades);
}
}

Output:

Grade for Student 102: B
Does Student 103 exist? true
Updated Grades: {101=A, 102=B, 103=B+}
After Removing Student 101: {102=B, 103=B+}
Total Students: 2
After Clearing: {}

Iterating Over a HashMap

Java provides multiple ways to iterate through a HashMap:

1) Using for-each loop: You can use a for-each loop with entrySet() to access both keys and values at the same time.

Example: Iterating Over a HashMap

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

public class HashMapIterationExample {
public static void main(String[] args) {
// Creating a HashMap of country codes and country names
Map<String, String> countries = new HashMap<>();
countries.put("IN", "India");
countries.put("US", "United States");
countries.put("JP", "Japan");

// Iterating using a for-each loop
System.out.println("For-Each Loop:");
for (Map.Entry<String, String> entry : countries.entrySet()) {
System.out.println(entry.getKey() + " => " + entry.getValue());
}
}
}

Output:

For-Each Loop:
IN => India
US => United States
JP => Japan

2) Using forEach() Method (Java 8+): Java 8 introduced the forEach() method, which allows you to iterate the map using lambda expressions.

// Iterating using forEach method
System.out.println("\nUsing forEach Method:");
countries.forEach((code, name) -> System.out.println(code + " => " + name));

Output:

Using forEach Method:
IN => India
US => United States
JP => Japan

3) Using an Iterator: For more control, you can use an Iterator with entrySet(). This method is useful if you want to remove entries while iterating.

For example:

import java.util.Iterator;

System.out.println("\nUsing Iterator:");
Iterator<Map.Entry<String, String>> iterator = countries.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
System.out.println(entry.getKey() + " => " + entry.getValue());
}

Output:

Using Iterator:
IN => India
US => United States
JP => Japan

Also Learn Important Topics of Java

Leave a Comment