HashMap in Java with Code Examples


HashMap is a fundamental data structure in Java, frequently used in various programming scenarios. It's a part of the Java Collections Framework and provides efficient key-value storage and retrieval. In this article, we'll explore HashMap in Java comprehensively, understanding its concept, usage, methods, and a hands-on example.
 

What is a HashMap?

 

A HashMap is a data structure that implements the Map interface in Java. It represents a collection of key-value pairs, where each key is associated with a unique value. HashMaps are known for their efficiency in retrieving values based on keys, making them suitable for scenarios where quick access to data is crucial. If you attempt to insert a value for a key that already exists in the map, the new value will override the previous value associated with that key.

 

Key Characteristics of HashMap

 

  1. Key-Value Pair: Each element in a HashMap consists of a key and a corresponding value. Keys must be unique, while values can be duplicate.
  2. Null Values: HashMap allows one null key and multiple null values.
  3. Unordered: The elements in a HashMap are not stored in a specific order. Unlike lists, which have an order, HashMaps store data based on the hash codes of keys, making retrieval efficient.
  4. Efficiency: HashMaps provide constant-time average complexity for basic operations like get and put, making them efficient for data retrieval.

 

Hashing

 

Hashing is a technique used in computer science to map data of arbitrary size to fixed-size values. It's a process of converting input (or 'key') into an index within a data structure (typically an array) where the corresponding value (or 'payload') can be found. The main idea behind hashing is to achieve efficient data retrieval.

 

How HashMap Utilizes Hashing?

In Java, a HashMap is a widely used data structure for storing key-value pairs. It relies on hashing to provide fast access to values associated with specific keys. Here's how it works:

 

1. Hash Function
  • When you add a key-value pair to a HashMap, the HashMap uses a hash function to determine the index (bucket) in the underlying array where the value should be stored.
  • The hash function takes the key and produces a hash code, which is an integer.
2. Index Calculation
  • The hash code is then modified to fit within the size of the array (the number of buckets). This is typically done using the modulo operation (%) to ensure the index is within bounds.
3. Collision Handling
  • Hash collisions occur when different keys produce the same hash code. To handle collisions, HashMap uses linked lists (or more recently, balanced trees for Java 8+).
  • If two keys produce the same index due to a collision, the key-value pairs are stored in a linked list (or tree) at that index.

 

How to Use HashMap in Java

 

Creating a HashMap

 

You can create a HashMap in Java using the HashMap class from the java.util package:

import java.util.HashMap;
// ...
HashMap<String, Integer> studentGrades = new HashMap<>();

Here, String represents the data type for keys, and Integer represents the data type for values.

 

Adding Key-Value Pairs

 

To add key-value pairs to a HashMap, you can use the put method:

studentGrades.put("Alice", 95);
studentGrades.put("Bob", 88);
studentGrades.put("Charlie", 92);

 

Retrieving Values

 

You can retrieve values from a HashMap using the get method:

int aliceGrade = studentGrades.get("Alice");
System.out.println("Alice's Grade: " + aliceGrade); 

// Output: Alice's Grade: 95

 

Iterating Through a HashMap

 

To iterate through the key-value pairs in a HashMap, you can use a for-each loop:

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

 

Checking if a Key Exists

 

You can check if a key exists in a HashMap using the containsKey method:

boolean containsAlice = studentGrades.containsKey("Alice");
System.out.println("Contains Alice? " + containsAlice); 

// Output: Contains Alice? true

 

Removing Key-Value Pairs

 

To remove a key-value pair from a HashMap, you can use the remove method:

studentGrades.remove("Bob");

 

Example: Using HashMap to Store Student Grades

 

Here's a complete Java program that demonstrates the use of a HashMap to store and manage student grades

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

public class StudentGrades {
   public static void main(String[] args) {
       // Create a HashMap to store student grades
       HashMap<String, Integer> studentGrades = new HashMap<>();

       // Add student grades
       studentGrades.put("Alice", 95);
       studentGrades.put("Bob", 88);
       studentGrades.put("Charlie", 92);

       // Retrieve and print grades
       int aliceGrade = studentGrades.get("Alice");
       int bobGrade = studentGrades.get("Bob");
       int charlieGrade = studentGrades.get("Charlie");

       System.out.println("Alice's Grade: " + aliceGrade);
       System.out.println("Bob's Grade: " + bobGrade);
       System.out.println("Charlie's Grade: " + charlieGrade);

       // Iterate through the HashMap
       System.out.println("Student Grades:");
       for (Map.Entry<String, Integer> entry : studentGrades.entrySet()) {
           System.out.println(entry.getKey() + ": " + entry.getValue());
       }

       // Check if a key exists
       boolean containsAlice = studentGrades.containsKey("Alice");
       System.out.println("Contains Alice? " + containsAlice);

       // Remove a student
       studentGrades.remove("Bob");
       System.out.println("Bob's Grade Removed.");
   }
}

Output

Alice's Grade: 95
Bob's Grade: 88
Charlie's Grade: 92
Student Grades:
Alice: 95
Bob: 88
Charlie: 92
Contains Alice? true
Bob's Grade Removed.

 

Summary

 

HashMap is a versatile and efficient data structure in Java for storing and retrieving key-value pairs. Understanding how to create, add, retrieve, and manipulate data in a HashMap is valuable for a wide range of programming tasks.



Thanks for feedback.



Read More....
Java Exception Handling
Java : HashSet and LinkedHashSet
Inner classes in Java
Java Collections Framework
Java Data Types and Variables - Declaration and Initialization