codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
☕

Java Programming

54 / 65 topics
50Java Collections51Java ArrayList52Java LinkedList53Java HashSet54Java HashMap55Java Iterator
Tutorials/Java Programming/Java HashMap
☕Java Programming

Java HashMap

Updated 2026-05-12
30 min read

Java HashMap

In this tutorial, we will explore the HashMap class in Java, which is part of the Java Collections Framework. A HashMap is a collection that stores key-value pairs and allows for fast retrieval based on keys. Understanding how to use HashMap is crucial for many applications, from simple data storage to complex algorithms.

Introduction

A HashMap is an implementation of the Map interface in Java. It uses a hash table to store its elements, which provides average constant-time performance for basic operations like add, remove, and lookup. This makes it very efficient for scenarios where you need quick access to data based on unique keys.

In this tutorial, we will cover how to create a HashMap, add key-value pairs, remove entries, and iterate through the keys and values. By the end of this tutorial, you'll have a solid understanding of how to use HashMap in your Java programs.

Core Content

1. Creating a HashMap

To create a HashMap, you need to specify the types of keys and values it will store. Here's a simple example:

CreateHashMap.java
1import java.util.HashMap;
2
3public class CreateHashMap {
4 public static void main(String[] args) {
5 // Creating a HashMap with String keys and Integer values
6 HashMap<String, Integer> map = new HashMap<>();
7
8 // Adding key-value pairs to the HashMap
9 map.put("Apple", 10);
10 map.put("Banana", 20);
11 map.put("Cherry", 30);
12
13 // Printing the HashMap
14 System.out.println(map);
15 };
16}
Output
{Apple=10, Banana=20, Cherry=30}

2. Adding Key-Value Pairs

You can add key-value pairs to a HashMap using the put method. If the key already exists in the map, its value will be updated.

AddKeyValue.java
1import java.util.HashMap;
2
3public class AddKeyValue {
4 public static void main(String[] args) {
5 HashMap<String, Integer> map = new HashMap<>();
6
7 // Adding initial key-value pairs
8 map.put("Apple", 10);
9 map.put("Banana", 20);
10
11 // Updating the value of an existing key
12 map.put("Apple", 15);
13
14 // Adding a new key-value pair
15 map.put("Cherry", 30);
16
17 // Printing the updated HashMap
18 System.out.println(map);
19 }
20}
Output
{Apple=15, Banana=20, Cherry=30}

3. Removing Key-Value Pairs

To remove a key-value pair from a HashMap, you can use the remove method, which takes the key as an argument.

RemoveKeyValue.java
1import java.util.HashMap;
2
3public class RemoveKeyValue {
4 public static void main(String[] args) {
5 HashMap<String, Integer> map = new HashMap<>();
6
7 // Adding initial key-value pairs
8 map.put("Apple", 10);
9 map.put("Banana", 20);
10 map.put("Cherry", 30);
11
12 // Removing a key-value pair
13 map.remove("Banana");
14
15 // Printing the updated HashMap
16 System.out.println(map);
17 }
18}
Output
{Apple=10, Cherry=30}

4. Looping Through Keys and Values

You can loop through the keys or values of a HashMap using iterators or enhanced for loops.

Looping Through Keys

LoopThroughKeys.java
1import java.util.HashMap;
2import java.util.Set;
3
4public class LoopThroughKeys {
5 public static void main(String[] args) {
6 HashMap<String, Integer> map = new HashMap<>();
7 map.put("Apple", 10);
8 map.put("Banana", 20);
9 map.put("Cherry", 30);
10
11 // Getting the set of keys
12 Set<String> keys = map.keySet();
13
14 // Looping through keys
15 for (String key : keys) {
16 System.out.println(key + ": " + map.get(key));
17 }
18 }
19}
Output
Apple: 10
Banana: 20
Cherry: 30

Looping Through Values

LoopThroughValues.java
1import java.util.HashMap;
2import java.util.Collection;
3
4public class LoopThroughValues {
5 public static void main(String[] args) {
6 HashMap<String, Integer> map = new HashMap<>();
7 map.put("Apple", 10);
8 map.put("Banana", 20);
9 map.put("Cherry", 30);
10
11 // Getting the collection of values
12 Collection<Integer> values = map.values();
13
14 // Looping through values
15 for (Integer value : values) {
16 System.out.println(value);
17 }
18 }
19}
Output
10
20
30

5. Common Mistakes and Pitfalls

  • Null Keys and Values: HashMap allows one null key and multiple null values.
  • Duplicate Keys: If you try to add a duplicate key, the old value will be replaced by the new value.
  • Performance Considerations: While HashMap is generally fast, it can degrade in performance if the hash function causes many collisions.

Practical Example

Let's create a practical example where we use a HashMap to store and manage a list of students with their respective grades.

StudentGrades.java
1import java.util.HashMap;
2import java.util.Scanner;
3
4public class StudentGrades {
5 public static void main(String[] args) {
6 HashMap<String, Integer> studentGrades = new HashMap<>();
7 Scanner scanner = new Scanner(System.in);
8
9 // Adding students and their grades
10 System.out.println("Enter student names and grades (type 'exit' to finish):");
11 while (true) {
12 System.out.print("Student name: ");
13 String name = scanner.nextLine();
14 if (name.equalsIgnoreCase("exit")) break;
15
16 System.out.print("Grade: ");
17 int grade = Integer.parseInt(scanner.nextLine());
18
19 studentGrades.put(name, grade);
20 }
21
22 // Displaying all students and their grades
23 System.out.println("
24Student Grades:");
25 for (String student : studentGrades.keySet()) {
26 System.out.println(student + ": " + studentGrades.get(student));
27 }
28 }
29}
Output
Enter student names and grades (type 'exit' to finish):
Student name: Alice
Grade: 95
Student name: Bob
Grade: 88
Student name: Charlie
Grade: 92
Student name: exit

Student Grades:
Alice: 95
Bob: 88
Charlie: 92

Summary

In this tutorial, we learned how to use Java's HashMap class for storing key-value pairs. We covered creating a HashMap, adding and removing entries, and looping through keys and values. Here are the key takeaways:

  • Creating a HashMap: Use new HashMap<>().
  • Adding Key-Value Pairs: Use put(key, value).
  • Removing Key-Value Pairs: Use remove(key).
  • Looping Through Keys/Values: Use keySet() and values().

Understanding how to use HashMap is essential for handling data efficiently in Java applications. In the next tutorial, we will explore how to iterate over collections using iterators, providing more control over traversal.

What's Next?

In the next tutorial, we will delve into the concept of iteration in Java with the help of the Iterator interface and its implementations. This will allow us to traverse collections in a more controlled manner. Stay tuned!


PreviousJava HashSetNext Java Iterator

Recommended Gear

Java HashSetJava Iterator