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.
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.
To create a HashMap, you need to specify the types of keys and values it will store. Here's a simple example:
1import java.util.HashMap;23public class CreateHashMap {4public static void main(String[] args) {5// Creating a HashMap with String keys and Integer values6HashMap<String, Integer> map = new HashMap<>();78// Adding key-value pairs to the HashMap9map.put("Apple", 10);10map.put("Banana", 20);11map.put("Cherry", 30);1213// Printing the HashMap14System.out.println(map);15};16}
{Apple=10, Banana=20, Cherry=30}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.
1import java.util.HashMap;23public class AddKeyValue {4public static void main(String[] args) {5HashMap<String, Integer> map = new HashMap<>();67// Adding initial key-value pairs8map.put("Apple", 10);9map.put("Banana", 20);1011// Updating the value of an existing key12map.put("Apple", 15);1314// Adding a new key-value pair15map.put("Cherry", 30);1617// Printing the updated HashMap18System.out.println(map);19}20}
{Apple=15, Banana=20, Cherry=30}To remove a key-value pair from a HashMap, you can use the remove method, which takes the key as an argument.
1import java.util.HashMap;23public class RemoveKeyValue {4public static void main(String[] args) {5HashMap<String, Integer> map = new HashMap<>();67// Adding initial key-value pairs8map.put("Apple", 10);9map.put("Banana", 20);10map.put("Cherry", 30);1112// Removing a key-value pair13map.remove("Banana");1415// Printing the updated HashMap16System.out.println(map);17}18}
{Apple=10, Cherry=30}You can loop through the keys or values of a HashMap using iterators or enhanced for loops.
1import java.util.HashMap;2import java.util.Set;34public class LoopThroughKeys {5public static void main(String[] args) {6HashMap<String, Integer> map = new HashMap<>();7map.put("Apple", 10);8map.put("Banana", 20);9map.put("Cherry", 30);1011// Getting the set of keys12Set<String> keys = map.keySet();1314// Looping through keys15for (String key : keys) {16System.out.println(key + ": " + map.get(key));17}18}19}
Apple: 10 Banana: 20 Cherry: 30
1import java.util.HashMap;2import java.util.Collection;34public class LoopThroughValues {5public static void main(String[] args) {6HashMap<String, Integer> map = new HashMap<>();7map.put("Apple", 10);8map.put("Banana", 20);9map.put("Cherry", 30);1011// Getting the collection of values12Collection<Integer> values = map.values();1314// Looping through values15for (Integer value : values) {16System.out.println(value);17}18}19}
10 20 30
HashMap allows one null key and multiple null values.HashMap is generally fast, it can degrade in performance if the hash function causes many collisions.Let's create a practical example where we use a HashMap to store and manage a list of students with their respective grades.
1import java.util.HashMap;2import java.util.Scanner;34public class StudentGrades {5public static void main(String[] args) {6HashMap<String, Integer> studentGrades = new HashMap<>();7Scanner scanner = new Scanner(System.in);89// Adding students and their grades10System.out.println("Enter student names and grades (type 'exit' to finish):");11while (true) {12System.out.print("Student name: ");13String name = scanner.nextLine();14if (name.equalsIgnoreCase("exit")) break;1516System.out.print("Grade: ");17int grade = Integer.parseInt(scanner.nextLine());1819studentGrades.put(name, grade);20}2122// Displaying all students and their grades23System.out.println("24Student Grades:");25for (String student : studentGrades.keySet()) {26System.out.println(student + ": " + studentGrades.get(student));27}28}29}
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
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:
new HashMap<>().put(key, value).remove(key).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.
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!